/ Published in: JavaScript

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).
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
function rgb2hex(r,g,b) { var rgb = [r.toString(16),g.toString(16),b.toString(16)] for (var i=0;i<3;i++) { if (rgb[i].length==1) rgb[i]=rgb[i]+rgb[i]; } if(rgb[0][0]==rgb[0][1] && rgb[1][0]==rgb[1][1] && rgb[2][0]==rgb[2][1]) return '#'+rgb[0][0]+rgb[1][0]+rgb[2][0]; return '#'+rgb[0]+rgb[1]+rgb[2]; } // Example var hex = rgb2hex(255, 170, 0); document.write("<pre>rgb(255,170,0) \u2192 "+hex+"</pre>");
URL: http://sverri.tumblr.com/post/865949154/javascript-rgb-to-hex-converter
Comments
