7

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

vsync
  • 118,978
  • 58
  • 307
  • 400
Mohsen
  • 64,437
  • 34
  • 159
  • 186

1 Answers1

20

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

user123444555621
  • 148,182
  • 27
  • 114
  • 126
  • Thank you very much! That was great idea. HSL is the best color system I've seen. I've made something based on your help here: http://jsfiddle.net/NzTUB/ Please check it out and tell me why Hue do not work properly? I think the rand function is not good enough for hue while hue accept values more than 100. – Mohsen May 02 '11 at 08:20
  • You need to make sure that the input field's values are passed as Numbers, not as strings - otherwise my `rand()` function messes up. Or replace it by `function rand(min, max) { min = parseFloat(min); max = parseFloat(max); return parseInt(Math.random() * (max-min+1), 10) + min; }` – user123444555621 May 02 '11 at 08:45