The top rated answer by Tim Down provides the best solution I can see for conversion to RGB. I like this solution for Hex conversion better though because it provides the most succinct bounds checking and zero padding for conversion to Hex.
function RGBtoHex (red, green, blue) {
red = Math.max(0, Math.min(~~this.red, 255));
green = Math.max(0, Math.min(~~this.green, 255));
blue = Math.max(0, Math.min(~~this.blue, 255));
return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);
};
The use of left shift '<<' and or '|' operators make this a fun solution too.
Here's a version of hexToRgb() that also parses a shorthand hex triplet such as "#03F":
function hexToRgb(hex) {
// Expand shorthand form (e.g. "03F") to 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";
Note that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code.
The top rated answer by Tim Down provides the best solution I can see for conversion to RGB. I like this solution for Hex conversion better though because it provides the most succinct bounds checking and zero padding for conversion to Hex.
The use of left shift '<<' and or '|' operators make this a fun solution too.
The following will do to the RGB to hex conversion and add any required zero padding:
Converting the other way:
Finally, an alternative version of
rgbToHex()
, as discussed in @casablanca's answer and suggested in the comments by @cwolves:Update 3 December 2012
Here's a version of
hexToRgb()
that also parses a shorthand hex triplet such as "#03F":For 3 digits hexToRgb function of Tim Down can be improved as below:
While this answer is unlikely to fit the question perfectly it may be very useful none the less.
var toRgb = document.createElement('div');
toRg.style.color = "hsl(120, 60%, 70%)";
> toRgb.style.color;
< "rgb(133, 225, 133)"
Your color has been converted to RgbWorks for: Hsl, Hex
Does not work for: Named colors
ECMAScript 6 version of Tim Down's answer
Converting RGB to hex
Converting hex to RGB
Returns an array
[r, g, b]
. Works also with shorthand hex triplets such as"#03F"
.Bonus: RGB to hex using
padStart()
methodNote that this answer uses latest ECMAScript features, which are not supported in older browsers. If you want this code to work in all environments, you should use Babel to compile your code.
If you need compare two color values (given as rgb,name color or hex value) or convert to HEX use HTML5 canvas object.