Pregunta

I've been reading the questions here about how to generate random colors in JS/JQuery. But I want to generate only darken colors avoiding the black, yellow and gray range colors, in order to be able to draw areas in google maps with different colors.

Thanks

¿Fue útil?

Solución

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.

Otros consejos

According to duplicate taken from comment of jj__?

function getGMapRandomColor() {
    return 'hsla(' + Math.floor(Math.random()*360) + ', 100%, 70%, 1)';
} 

First define the RGB ranges you do want, and once you have those defines just generate random values within those ranges. Or define the ranges you don't want and keep looping till you find a colour that fits those criteria, a lot less efficient, but quite a bit easier to program if efficiency is not an issue.

Where's the problem? Just generate 3 random numbers, maybe in the range from, let's say 30 to 150, so you will only get relatively low values for R, G and B, and block "black-like" colors. Then you would just have to check if these three values fall into the range of your defined blacklisted color ranges like yellow or gray.

For simplicity of implementation and thoroughness, I can't recommend this script highly enough:

David Merfeld's randomColor

Choose between hex or rgb, add in some alpha, specify light or dark palettes, avoid repeats, etc.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top