javascript - RGB to Hex and Hex to RGB -
how convert colors in rgb format hex format , vice versa?
for example, convert '#0080c0' (0, 128, 192).
the following rgb hex conversion , add required 0 padding:
function componenttohex(c) { var hex = c.tostring(16); return hex.length == 1 ? "0" + hex : hex; } function rgbtohex(r, g, b) { return "#" + componenttohex(r) + componenttohex(g) + componenttohex(b); } alert( rgbtohex(0, 51, 255) ); // #0033ff converting other way:
function hextorgb(hex) { var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseint(result[1], 16), g: parseint(result[2], 16), b: parseint(result[3], 16) } : null; } alert( hextorgb("#0033ff").g ); // "51"; finally, alternative version of rgbtohex(), discussed in @casablanca's answer , suggested in comments @cwolves:
function rgbtohex(r, g, b) { return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).tostring(16).slice(1); } update 3 december 2012
here's version of hextorgb() parses shorthand hex triplet such "#03f":
function hextorgb(hex) { // expand shorthand form (e.g. "03f") full form (e.g. "0033ff") var shorthandregex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandregex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseint(result[1], 16), g: parseint(result[2], 16), b: parseint(result[3], 16) } : null; } alert( hextorgb("#0033ff").g ); // "51"; alert( hextorgb("#03f").g ); // "51";
Comments
Post a Comment