I can't resist sharing this for those who may be writing some modern functional/compositional js using ES6. Here are some slick one-liners I am using in a color module that does color interpolation for data visualization.
Note that this does not handle the alpha channel at all.
function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
Edit: 3/28/2017
Here is another approach that seems to be even faster
function hexToRgbNew(hex) {
var arrBuff = new ArrayBuffer(4);
var vw = new DataView(arrBuff);
vw.setUint32(0,parseInt(hex, 16),false);
var arrByte = new Uint8Array(arrBuff);
return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}
Edit: 8/11/2017
The new approach above after more testing is not faster :(. Though it is a fun alternate way.
@ Tim, to add to your answer (its a little awkward fitting this into a comment).
As written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.
I'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.
function rgbToHex(r, g, b) {
if(r < 0 || r > 255) alert("r is out of bounds; "+r);
if(g < 0 || g > 255) alert("g is out of bounds; "+g);
if(b < 0 || b > 255) alert("b is out of bounds; "+b);
return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1,7);
}
(2017) SIMPLE ES6 composable arrow functions
I can't resist sharing this for those who may be writing some modern functional/compositional js using ES6. Here are some slick one-liners I am using in a color module that does color interpolation for data visualization.
Note that this does not handle the alpha channel at all.
May you be after something like this?
displays #9687c8
For convert directly from jQuery you can try:
An alternative version of hexToRgb:
Edit: 3/28/2017 Here is another approach
that seems to be even fasterEdit: 8/11/2017 The new approach above after more testing is not faster :(. Though it is a fun alternate way.
Here's my version:
@ Tim, to add to your answer (its a little awkward fitting this into a comment).
As written, I found the rgbToHex function returns a string with elements after the point and it requires that the r, g, b values fall within the range 0-255.
I'm sure this may seem obvious to most, but it took two hours for me to figure out and by then the original method had ballooned to 7 lines before I realised my problem was elsewhere. So in the interests of saving others time & hassle, here's my slightly amended code that checks the pre-requisites and trims off the extraneous bits of the string.