我一直在阅读有关如何在 JS/JQuery 中生成随机颜色的问题。但我只想生成较暗的颜色,避免使用黑色、黄色和灰色范围的颜色,以便能够在谷歌地图中绘制不同颜色的区域。
谢谢
我一直在阅读有关如何在 JS/JQuery 中生成随机颜色的问题。但我只想生成较暗的颜色,避免使用黑色、黄色和灰色范围的颜色,以便能够在谷歌地图中绘制不同颜色的区域。
谢谢
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];
}
在这里,ands
的l
范围从0
to 1
,r
和from tog
和from to 。b
0
255
h
0
359
根据从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.