views:

102

answers:

2

How do you extract the hue component of a color given as '#rrggbb'?

+2  A: 

The wikipedia article has a formula which looks like something that can easily be implemented:

http://en.wikipedia.org/wiki/Hue#Computing_hue_from_RGB

Edit: here's a function which uses those formulas:

function getHue(color) {
  var r = parseInt(color.substring(0,2),16)/255;
  var g = parseInt(color.substring(2,4),16)/255;
  var b = parseInt(color.substring(4,6),16)/255;

  var hue;
  if ((r >= g) && (g >= b)) {
      hue = 60*(g-b)/(r-b);
  } else if ((g > r) && (r >= b)) {
      hue = 60*(2 - (r-b)/(g-b));
  }
  //... continue here
  return hue;
}

alert(getHue('FF0000')); // correctly returns 0
alert(getHue('408000')); // correctly returns 90
alert(getHue('0000FF')); // not implemented yet

Just continue using the formulas from the table in that wikipedia article for other angles.

Sergey
+4  A: 
josh3736