Skip to content

Instantly share code, notes, and snippets.

@Gerst20051
Forked from JordanDelcros/combine-rgba-colors.js
Last active October 4, 2017 00:31
Show Gist options
  • Save Gerst20051/8e38e19fd15e53124941a41fe1c924c7 to your computer and use it in GitHub Desktop.
Save Gerst20051/8e38e19fd15e53124941a41fe1c924c7 to your computer and use it in GitHub Desktop.
Combine two RGBA colors with JavaScript
function blendColors() {
/* https://gist.github.com/JordanDelcros/518396da1c13f75ee057 */
var args = [ ...arguments ];
var base = [ 0, 0, 0, 0 ];
var mix;
var added;
while (added = args.shift()) {
if (typeof added[3] === 'undefined') {
added[3] = 1;
}
if (base[3] && added[3]) { // check if both alpha channels exist.
mix = [ 0, 0, 0, 0 ];
mix[3] = 1 - (1 - added[3]) * (1 - base[3]); // alpha
mix[0] = Math.round((added[0] * added[3] / mix[3]) + (base[0] * base[3] * (1 - added[3]) / mix[3])); // red
mix[1] = Math.round((added[1] * added[3] / mix[3]) + (base[1] * base[3] * (1 - added[3]) / mix[3])); // green
mix[2] = Math.round((added[2] * added[3] / mix[3]) + (base[2] * base[3] * (1 - added[3]) / mix[3])); // blue
} else if (added) {
mix = added;
} else {
mix = base;
}
base = mix;
}
return mix;
}
/* blendColors([ 69, 109, 160, 1 ], [ 61, 47, 82, 0.8 ]); // will return [ 63, 59, 98, 1 ] */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment