RGB to HEX converter


/ Published in: JavaScript
Save to your folder(s)

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).


Copy this code and paste it in your HTML
  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>");

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.