0

我一直在阅读有关如何在 JS/JQuery 中生成随机颜色的问题。但我只想生成较暗的颜色,避免使用黑色、黄色和灰色范围的颜色,以便能够在谷歌地图中绘制不同颜色的区域。

谢谢

4

5 回答 5

3
var hue = Math.floor(Math.random() * 360),
    saturation =  Math.floor(Math.random() * 100),
    lightness =  Math.floor(Math.random() * 50),
    color = "hsl(" + hue + ", " + saturation + "%, " + lightness + "%)";

那是生成随机的 hsl 颜色。但是,如果您想使现有的 rgb 颜色变暗,最好的办法是将其转换为 hsl,然后根据您的需要设置其亮度值。享受这些功能的乐趣:

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];
}

在这里,andsl范围从0to 1r和from tog和from to 。b0255h0359

于 2013-06-27T08:59:07.590 回答
2

根据从jj__的评论中获取的副本?

function getGMapRandomColor() {
    return 'hsla(' + Math.floor(Math.random()*360) + ', 100%, 70%, 1)';
} 
于 2014-12-06T13:02:01.687 回答
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.

于 2013-06-27T09:00:09.353 回答
1

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.

于 2013-06-27T09:00:10.153 回答
0

为了实现的简单性和彻底性,我不能高度推荐这个脚本:

大卫默菲尔德的随机颜色

在 hex 或 rgb 之间进行选择,添加一些 alpha,指定浅色或深色调色板,避免重复等。

于 2017-06-03T18:57:18.460 回答