Skip to content

Instantly share code, notes, and snippets.

@fvicente
Last active August 5, 2017 00:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fvicente/1cf249e113ed180fa6e3a37f578c1065 to your computer and use it in GitHub Desktop.
Save fvicente/1cf249e113ed180fa6e3a37f578c1065 to your computer and use it in GitHub Desktop.
RGB opacity calculator
function colorHexToRGB(htmlColor) {
var COLOR_REGEX = /^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/;
var arrRGB = htmlColor.match(COLOR_REGEX);
if (arrRGB === null) {
alert("Invalid color passed, the color should be in the html format. Example: #ff0033");
return null;
}
var red = parseInt(arrRGB[1], 16);
var green = parseInt(arrRGB[2], 16);
var blue = parseInt(arrRGB[3], 16);
return {"r": red, "g": green, "b": blue};
}
function colorRGBToHex(red, green, blue) {
if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) {
alert("Invalid color value passed. Should be between 0 and 255.");
return null;
}
var formatHex = function(value) {
value = value + "";
if (value.length == 1) {
return "0" + value;
}
return value;
}
var hexRed = formatHex(red.toString(16));
var hexGreen = formatHex(green.toString(16));
var hexBlue = formatHex(blue.toString(16));
return "#" + hexRed + hexGreen + hexBlue;
}
function convert(desired, background, opacity) {
var rgb = colorHexToRGB(desired);
if (!rgb) {
return null;
}
var bkg = colorHexToRGB(background);
if (!bkg) {
return null;
}
opacity = opacity * 1.0 // ensure float
return colorRGBToHex(
parseInt((rgb.r - ((1 - opacity) * bkg.r)) / opacity),
parseInt((rgb.g - ((1 - opacity) * bkg.g)) / opacity),
parseInt((rgb.b - ((1 - opacity) * bkg.b)) / opacity)
)
}
let desiredColors = ['#95acf2', '#6f80b5', '#f89081', '#b26459', '#abee84', '#80b262', '#ebebeb', '#b0b0b0']
let opacity = 0.75
for (let color of desiredColors) {
console.log(convert(color, '#ffffff', opacity) + ' with ' + opacity + ' of opacity on white background, results in ' + color);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment