Skip to content

Instantly share code, notes, and snippets.

@rmwxiong
Forked from paulirish/gist:357048
Last active May 21, 2020 14:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rmwxiong/ad6e922dcc739a599640 to your computer and use it in GitHub Desktop.
Save rmwxiong/ad6e922dcc739a599640 to your computer and use it in GitHub Desktop.
Fix for color components with single digit values
// get the average color of two hex colors.
function avgcolor(color1,color2){
var avg = function(a,b){ return (a+b)/2; },
t16 = function(c){ return parseInt((''+c).replace('#',''),16) },
hex = function(c){ var t = (c>>0).toString(16);
return t.length == 2 ? t : '0' + t },
hex1 = t16(color1),
hex2 = t16(color2),
r = function(hex){ return hex >> 16 & 0xFF},
g = function(hex){ return hex >> 8 & 0xFF},
b = function(hex){ return hex & 0xFF},
res = '#' + hex(avg(r(hex1),r(hex2)))
+ hex(avg(g(hex1),g(hex2)))
+ hex(avg(b(hex1),b(hex2)));
return res;
}
// e.g.
avgcolor('#ffffff','#000000'); // "#7f7f7f"
@boisebuster
Copy link

This is wonderfully compact. Thanks so much for fixing the issue with the paulrish version. I'm totally clueless as to bitwise operators; how would you average an entire array, as opposed to just two at at time?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment