Recently, I needed to create a function that fades from one color to the other. CSS3 makes the job very easy by making use of the transition property. However I needed to use this functionality inside a canvas element, meaning I would have to calculate the transition in JavaScript.
CSS3 Method:
.selector { color:red; transition: color .5s; }.selector:hover { color:green; }
On the browsers, colors can be set using 3 types of notations: RGB, HEX, or HSL. I usually prefer using HEX notation (#34B620) but the only problem is I'd have to convert these numbers into integers I can manage first before I can animate a transition.
HEX to DEC
The numbers #34B620 need to be translated into rgb(52, 182, 32). To do so, we can create a function that convert Hex into integers.
function convertColor(hexa){
var chunks = [];
var tmp,i;
hexa = hexa.substr(1); // remove the pound
if ( hexa.length === 3){
tmp = hexa.split("");
for(i=0;i<3;i++){
chunks.push(parseInt(tmp[i]+""+tmp[i],16));
}
}else if (hexa.length === 6){
tmp = hexa.match(/.{2}/g);
for(i=0;i<3;i++){
chunks.push(parseInt(tmp[i],16));
}
}else {
throw new Error("'"+hexa+"' is not a valid hex format");
}
return chunks;
}
This function can properly convert hexadecimal numbers if they come in 3 digit format and 6 digit format.
convertColor("#00FF00");
// [0, 255, 0]
convertColor("#0639FF");
// [6, 57, 255]
convertColor("#06D");
// [0, 102, 221]
Now that I have integers I can work with, I can easily create a transition from color to color.
DEC to HEX
The opposite is much easier to do. We can simply call a .toString() method with the argument 16 for hex on a number.
var decnumber = 12;
var hexnumber = decnumber.toString(16);
// C
To convert the colors to hex we can simply loop through the values we converted earlier and call toString():
function convertToHexColor(decArray){
var i,l = decArray.length,
hexColor = "#";
for (i=0;i<l;i++){
hexColor += decArray[i].toString(16);
}
return hexColor;
}
That's it, we now know how to convert from hex to dec and from dec to hex using JavaScript.
Join the Conversation