1

I want to randomly generate a color hex code with Javascript. This color needs to be light enough to place black font on it.

What is the best way to ensure a light color is being generated? Will it help to limit letters in the following function?

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split(''),
        color = '#';
    for(var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}
DonJuwe
  • 4,477
  • 3
  • 34
  • 59
  • limiting to letters will only ensure you have a valid color code, nothing about lightness. Hint: the lightness of a color is the sum of the values of all the color channels. – doldt Apr 07 '15 at 12:30
  • Use hsl() with fixed saturation and luminosity and a random hue. What's with the hex values in those answers? we're not in the 1990's anymore :p – Touffy Apr 07 '15 at 12:37

2 Answers2

3

This stack answer seems like it would work good for you. One such answer uses:

var randomColor = (function lol(m, s, c) {
    return s[m.floor(m.random() * s.length)] +
        (c && lol(m, s, c - 1));
})(Math, '3456789ABCDEF', 4);

JS Fiddle from the answer above.

Edit: Change this line to change how light/dark you'd like the random color to be (changing to ABCDEF will make them lighter):

})(Math, '3456789ABCDEF', 4);
Community
  • 1
  • 1
william.taylor.09
  • 2,145
  • 10
  • 17
2

If you can ignore IE8 and below you can get a random 'light' color in hsl, by randomly changing the hue and setting the saturation to 50% and the light component to 75%.

var lightColor='hsl('+Math.floor(Math.random()*361)+',50%,75%)';

var lightColor= 'hsl('+Math.floor(Math.random()*361)+',50%,75%)';

You can translate hsl color (near enough) to rgb if required for older browsers-

function hslToRgb(hsl){
    if(typeof hsl== 'string'){
        hsl= hsl.match(/(\d+(\.\d+)?)/g);
    }
    var sub, h= hsl[0]/360, s= hsl[1]/100, l= hsl[2]/100, 
    t1, t2, t3, rgb, val;
    if(s== 0){
        val= Math.round(l*255).minmax(0, 255);
        rgb= [val, val, val];
    }
    else{
        if(l<0.5)   t2= l*(1 + s);
        else t2= l + s - l*s;
        t1= 2*l - t2;
        rgb= [0, 0, 0];
        for(var i= 0; i<3; i++){
            t3= h + 1/3*-(i - 1);
            t3<0 && t3++;
            t3>1 && t3--;
            if(6*t3<1) val= t1 +(t2 - t1)*6*t3;
            else if(2*t3<1) val= t2;
            else if(3*t3<2) val= t1 +(t2 - t1)*(2/3 - t3)*6;
            else val= t1;
            rgb[i]= Math.round(val*255).minmax(0, 255);
        }
    }
    return 'rgb('+rgb.join(',')+')';
}

lightColor+'~= '+hslToRgb(lightColor);

/* returned value: (String) hsl(88,50%,75%)~= rgb(193,223,159) */

kennebec
  • 102,654
  • 32
  • 106
  • 127