Posted By

Roshambo on 04/29/09


Tagged

color conversion RGB hsv hsb


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

Jamie
ap3x
timmotheus


HSV to RGB


 / Published in: JavaScript
 

HSV to RGB color conversion. Ported from the excellent java algorithm by Eugene Vishnevsky at: http://www.cs.rit.edu/~ncs/color/t_convert.html.

  1. /**
  2.  * HSV to RGB color conversion
  3.  *
  4.  * H runs from 0 to 360 degrees
  5.  * S and V run from 0 to 100
  6.  *
  7.  * Ported from the excellent java algorithm by Eugene Vishnevsky at:
  8.  * http://www.cs.rit.edu/~ncs/color/t_convert.html
  9.  */
  10. function hsvToRgb(h, s, v) {
  11. var r, g, b;
  12. var i;
  13. var f, p, q, t;
  14.  
  15. // Make sure our arguments stay in-range
  16. h = Math.max(0, Math.min(360, h));
  17. s = Math.max(0, Math.min(100, s));
  18. v = Math.max(0, Math.min(100, v));
  19.  
  20. // We accept saturation and value arguments from 0 to 100 because that's
  21. // how Photoshop represents those values. Internally, however, the
  22. // saturation and value are calculated from a range of 0 to 1. We make
  23. // That conversion here.
  24. s /= 100;
  25. v /= 100;
  26.  
  27. if(s == 0) {
  28. // Achromatic (grey)
  29. r = g = b = v;
  30. return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
  31. }
  32.  
  33. h /= 60; // sector 0 to 5
  34. i = Math.floor(h);
  35. f = h - i; // factorial part of h
  36. p = v * (1 - s);
  37. q = v * (1 - s * f);
  38. t = v * (1 - s * (1 - f));
  39.  
  40. switch(i) {
  41. case 0:
  42. r = v;
  43. g = t;
  44. b = p;
  45. break;
  46.  
  47. case 1:
  48. r = q;
  49. g = v;
  50. b = p;
  51. break;
  52.  
  53. case 2:
  54. r = p;
  55. g = v;
  56. b = t;
  57. break;
  58.  
  59. case 3:
  60. r = p;
  61. g = q;
  62. b = v;
  63. break;
  64.  
  65. case 4:
  66. r = t;
  67. g = p;
  68. b = v;
  69. break;
  70.  
  71. default: // case 5:
  72. r = v;
  73. g = p;
  74. b = q;
  75. }
  76.  
  77. return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
  78. }

Report this snippet  

You need to login to post a comment.