var hue = Math.floor(Math.random() * 360),
saturation = Math.floor(Math.random() * 100),
lightness = Math.floor(Math.random() * 50),
color = "hsl(" + hue + ", " + saturation + "%, " + lightness + "%)";
That was to generate a random hsl color. But if you want to darken an existing rgb color the best thing to do is to convert it to hsl and then setting its lightness value according to your needs. Have fun with these functions:
function rgbToHsl(r, g, b) {
var maxRGB = Math.max(r, g, b),
minRGB = Math.min(r, g, b),
tmp, h, s, l;
tmp = maxRGB - minRGB;
l = (maxRGB + minRGB)/255;
if (tmp) {
s = Math.round(tmp/(l < 1 ? l : 2 - l))/255;
if (r === maxRGB) h = (g - b)/tmp;
else if (g === maxRGB) h = 2 + (b - r)/tmp;
else h = 4 + (r - g)/tmp;
h = (h < 0 ? h + 6 : h)*60 % 360;
} else h = s = 0;
l /= 2;
return [h, s, l];
}
function hslToRgb(h, s, l) {
if (!s) return r = g = b = l*255;
var q = l < .5 ? l*(1 + s) : l + s - l*s,
p = 2*l - q;
for (var i = 120, t, c = []; i >= -120; i -= 120) {
t = h + i;
if (t < 0) t += 360;
else if (t >= 360) t -= 360;
if (t < 60) c.push(p + (q - p)*t/60);
else if (t < 180) c.push(q);
else if (t < 240) c.push(p + (q - p)*(240 - t)/60);
else c.push(p);
}
return [c[0]*255, c[1]*255, c[2]*255];
}
Here, s
and l
ranges from 0
to 1
, r
, g
and b
from 0
to 255
and h
from 0
to 359
.