Skip to content

Instantly share code, notes, and snippets.

@paulirish
Created April 6, 2010 00:28
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save paulirish/357048 to your computer and use it in GitHub Desktop.
Save paulirish/357048 to your computer and use it in GitHub Desktop.
average hex color
// 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){ return (c>>0).toString(16) },
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"
@rmwxiong
Copy link

This is super old, but this doesn't work properly if any of the color components have single digit values. i.e. #ff0505 becomes #ff55.

Made a fix here: https://gist.github.com/rmwxiong/ad6e922dcc739a599640/02854508d14e737e38293c5467d75c45843830c8

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