How to convert colors in RGB format to hex format and vice versa?
For example, convert \'#0080C0\'
to (0, 128, 192)
.
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.