Update from my Convert jQuery RGB output to Hex Color Post Modern browsers will soon support four and eight-digit hex colors, which means you now include an alpha channel with your color. As you can see in the comments of this CSS Tricks post, the alpha channel conversion is different from the other color channels and this makes it very confusing to convert:
- The
r
(red),g
(green), andb
(blue) channels have decimal values ranging from 0 to 255. - the
a
(alpha) channel has a decimal value that ranges from 0 to 100.
#RRGGBB
or #RRGGBBAA
hex code value. I've copied some of the above code from the rgb-hex node module, where I also contributed alpha channel support.
function rgb2hex(orig) {
var a, isPercent,
rgb = orig.replace(/\s/g, '').match(/^rgba?\((\d+),(\d+),(\d+),?([^,\s)]+)?/i),
alpha = (rgb && rgb[4] || "").trim(),
hex = rgb ? "#" +
(rgb[1] | 1 << 8).toString(16).slice(1) +
(rgb[2] | 1 << 8).toString(16).slice(1) +
(rgb[3] | 1 << 8).toString(16).slice(1) : orig;
if (alpha !== "") {
isPercent = alpha.indexOf("%") > -1;
a = parseFloat(alpha);
if (!isPercent && a >= 0 && a <= 1) {
a = Math.round(255 * a);
} else if (isPercent && a >= 0 && a <= 100) {
a = Math.round(255 * a / 100)
} else {
a = "";
}
}
if (a) {
hex += (a | 1 << 8).toString(16).slice(1);
}
return hex;
}