Cycymomo
7/29/2013 - 1:47 PM

Color utils

Color utils

// invert  color
function invertColor(color){
var inv = function(a){ return 255 - a; },
  t16  = function(c){ return parseInt((''+c).replace('#',''),16) },
  hex  = function(c){ return (c>>0).toString(16) },
  hex1 = t16(color),
  r    = function(hex){ return hex >> 16 & 0xFF},
  g    = function(hex){ return hex >> 8 & 0xFF},
  b    = function(hex){ return hex & 0xFF},
  res  = '#' + hex(inv(r(hex1))) 
             + hex(inv(g(hex1))) 
             + hex(inv(b(hex1)));
  return res;
}

invertColor('#ffffff'); // "#000000"
// 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;
}

avgcolor('#ffffff','#000000'); // "#7f7f7f"