@Diaco.AW
These are the kinds of color conversions I am talking about...
Strings vs Decimal values
"#FF0000" (Pure red) can also be written as 0xFF0000. Logging the value of 0xFF0000 reveals its decimal value.
console.log(0xFF0000);// logs 16711680
Extracting component RGB values
Using bitwise math, you can break a decimal value into three component colors.
function getComponentColors(color){
var red = (color >> 16) & 0xFF;
var green = (color >> 8) & 0xFF;
var blue = color % 0xFF;
return [red, green, blue];
}
getComponentColors(0xFF0000); //returns [255,0,0];
Converting RGB component values to HSL component values
function RGBtoHSL(r, g, {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, , min = Math.min(r, g, ;
var h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
}else{
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max){
case r: h = (g - / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [h, s, l];
}
RGBtoHSL(255,0,0);// returns [0,1,.5]; (saturation and lightness need to be multiplied by 100 for HSL() strings.
Converting HSL components to RGB component colors
HSL is nice for rotating colors around or adjusting saturation or brightness of colors... But sometimes you need to go back to RGB.
function HSLtoRGB(h, s, l){ var r, g, b;
if(s == 0){
r = g = b = l; // achromatic
}else{
function hue2rgb(p, q, t){
if(t < 0) t += 1;
if(t > 1) t -= 1;
if(t < 1/6) return p + (q - p) * 6 * t;
if(t < 1/2) return q;
if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
HSLtoRGB(0,1,.5); //returns [255,0,0]
Combining RGB component colors to get decimal
Individual RGB component values can be tweened as well, but you can convert them back to decimal values as well:
function combineRGB(r, g, {
return ( r << 16 ) | ( g << 8 ) | b ;
}
combineRGB(255,0,0); //returns 16711680
Getting Hex string from RGB decimal value
Finally, if you want to convert the decimal RGB value to a string...
var color=16711680;
var hexString=color.toString(16); // returns string "FF0000"