Based on:
Last active
August 5, 2017 00:07
-
-
Save fvicente/1cf249e113ed180fa6e3a37f578c1065 to your computer and use it in GitHub Desktop.
RGB opacity calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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