Javascript – Random Color Generator with Hue/Saturation and more controls

javascript

In this question I found a lot of interesting functions to generate random colors.

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:

function get_random_color() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}
$.each($('div'),function(){
    $(this).css('background-color', get_random_color());
});

Thanks

Best Answer

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 + '%)';
}

http://jsfiddle.net/5V8mV/1/

With that algorithm, you can easily restrict the colors to bluish tones for example: http://jsfiddle.net/DH2Bk/

In case you need an RGB conversion algorithm (for IE8, for example), you'll find it directly in the specs: http://www.w3.org/TR/css3-color/#hsl-color

HOW TO RETURN hsl.to.rgb(h, s, l):
   SELECT:
     l<=0.5: PUT l*(s+1) IN m2
     ELSE: PUT l+s-l*s IN m2
   PUT l*2-m2 IN m1
   PUT hue.to.rgb(m1, m2, h+1/3) IN r
   PUT hue.to.rgb(m1, m2, h    ) IN g
   PUT hue.to.rgb(m1, m2, h-1/3) IN b
   RETURN (r, g, b)

HOW TO RETURN hue.to.rgb(m1, 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

Edit:

I just found a nice JS library with more options on https://github.com/davidmerfield/randomColor

Related Topic