Posted By

Sverri on 07/28/10


Tagged

hex Converter RGB


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

Cepreu
ap3x


RGB to HEX converter


 / Published in: JavaScript
 

URL: http://sverri.tumblr.com/post/865949154/javascript-rgb-to-hex-converter

Converts and returns the HEX equivalent of an RGB value. If it is possible the HEX shorthand will be returned (ie. #abc instead of #aabbcc).

  1. function rgb2hex(r,g,b) {
  2. var rgb = [r.toString(16),g.toString(16),b.toString(16)]
  3. for (var i=0;i<3;i++) {
  4. if (rgb[i].length==1) rgb[i]=rgb[i]+rgb[i];
  5. }
  6. if(rgb[0][0]==rgb[0][1] && rgb[1][0]==rgb[1][1] && rgb[2][0]==rgb[2][1])
  7. return '#'+rgb[0][0]+rgb[1][0]+rgb[2][0];
  8. return '#'+rgb[0]+rgb[1]+rgb[2];
  9. }
  10.  
  11. // Example
  12. var hex = rgb2hex(255, 170, 0);
  13. document.write("<pre>rgb(255,170,0) \u2192 "+hex+"</pre>");

Report this snippet  

You need to login to post a comment.