In this question I found a lot of interesting functions to generate random colors. But I need a random color generator that accept Hue, Saturation and Darkness range and also number of colors that we need. Actually I can write a random color generator but I don't have good understanding of relationship between color numbers and darkness, hue and saturation of a color. I want the function export colors in an array. I also made a jsfiddle file here for testing.


1 Answers

user123444555621 On Best Solutions

In CSS3 capable browsers, there's no need to transform HSL colors to RGB, since you can assign them just like that:

function rand(min, max) {
    return min + Math.random() * (max - min);

function get_random_color() {
    var h = rand(1, 360);
    var s = rand(0, 100);
    var l = rand(0, 100);
    return 'hsl(' + h + ',' + s + '%,' + l + '%)';

With that algorithm, you can easily restrict the colors to bluish tones for example:

In case you need an RGB conversion algorithm (for IE8, for example), you'll find it directly in the specs:

     l<=0.5: PUT l*(s+1) IN m2
     ELSE: PUT l+s-l*s IN m2
   PUT l*2-m2 IN m1
   PUT, m2, h+1/3) IN r
   PUT, m2, h    ) IN g
   PUT, m2, h-1/3) IN b
   RETURN (r, g, b)

HOW TO RETURN, m2, h): 
   IF h<0: PUT h+1 IN h
   IF h>1: PUT h-1 IN h
   IF h*6<1: RETURN m1+(m2-m1)*h*6
   IF h*2<1: RETURN m2
   IF h*3<2: RETURN m1+(m2-m1)*(2/3-h)*6
   RETURN m1


I just found a nice JS library with more options on