Last active
August 29, 2015 14:18
-
-
Save amoilanen/ac8ef9643346b6212052 to your computer and use it in GitHub Desktop.
JavaScript function to compute what color should be specified in CSS given desired transparency value and non-transparent color
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
/** | |
* Computes the color to be specified in CSS which will be visually equivalent to | |
* <b>desiredColor</b> when the transparency is <b>alpha</b>. | |
* Based on the method suggested in http://stackoverflow.com/questions/12228548/findinq-equivalent-color-with-opacity | |
* | |
* @options.backgroundColor - | |
* background color against which the computed background color will be overlayed | |
* @options.desiredColor - | |
* desired color appearance in case alpha is 1 | |
* @options.alpha - | |
* the opacity for which the color is calculated | |
*/ | |
function equivalentOpaqueColor(options) { | |
var backgroundColor = options.backgroundColor; | |
var desiredColor = options.desiredColor; | |
var alpha = options.alpha; | |
var equivalentColor = { | |
toString: function() { | |
var attributes = [this.r, this.g, this.b].join(', '); | |
return 'rgb(' + attributes + ')'; | |
} | |
}; | |
['r', 'g', 'b'].forEach(function(attr) { | |
var backgroundDifference = desiredColor[attr] - backgroundColor[attr]; | |
equivalentColor[attr] = (backgroundDifference + backgroundColor[attr] * alpha) / alpha; | |
}); | |
return equivalentColor; | |
} | |
function rgb(r, g, b) { | |
return { | |
r: r, | |
g: g, | |
b: b | |
}; | |
} | |
var color = equivalentOpaqueColor({ | |
backgroundColor: rgb(255, 255, 255), | |
desiredColor: rgb(180, 180, 180), | |
alpha: 0.5 | |
}); | |
console.log('Equivalent color = ', color.toString()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment