PDA

View Full Version : convert HSL to RGB using JS?


homerUK
12-08-2002, 08:17 PM
hi,

does anyone have, or know of any Javascript functions/code which will convert a "HSL" integer in to a HEX value..

:confused:

Our editor uses an ActiveX colour chooser... and the value it returns is an HSL one... eg: 8421631 in HSL format... but we want this as a hex value which is #ff0808

see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/commondialogboxlibrary/colordialogbox.asp for the actual description of it...

thanks for any help..!!

jkd
12-08-2002, 10:00 PM
I use something like this in my color picker script:


function hsl2rgb(h, s, l) {
var m1, m2, hue;
var r, g, b
s /=100;
l /= 100;
if (s == 0)
r = g = b = (l * 255);
else {
if (l <= 0.5)
m2 = l * (s + 1);
else
m2 = l + s - l * s;
m1 = l * 2 - m2;
hue = h / 360;
r = HueToRgb(m1, m2, hue + 1/3);
g = HueToRgb(m1, m2, hue);
b = HueToRgb(m1, m2, hue - 1/3);
}
return {r: r, g: g, b: b};
}

function HueToRgb(m1, m2, hue) {
var v;
if (hue < 0)
hue += 1;
else if (hue > 1)
hue -= 1;

if (6 * hue < 1)
v = m1 + (m2 - m1) * hue * 6;
else if (2 * hue < 1)
v = m2;
else if (3 * hue < 2)
v = m1 + (m2 - m1) * (2/3 - hue) * 6;
else
v = m1;

return 255 * v;
}


hsl2rgb expects arguments like so:

hsl2rgb(angle, sat, light)

Where angle is between 0 and 360, sat is between 0 and 100, and light is between 0 and 100.

homerUK
12-09-2002, 10:29 AM
hey cheers v much for that!!

the thing is... how do I seperate the HSL colour code?

I understand putting it in to your function to convert is as H, S and L... but, at the moment it is in a long integer format like "8421631" or "313120" so I dont know how to seperate these!!

Thanks heaps!!! :thumbsup: