我一直在阅读关于如何在JS/JQuery中生成随机颜色的问题。但我只想生成较暗的颜色,避免黑色,黄色和灰色范围的颜色,以便能够在谷歌地图中绘制不同颜色的区域。
谢谢
发布于 2013-06-27 16:59:08
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];
}这里,s和l的范围从0到1,从r、g和b,从0到255,以及<代码>d11从d12到359。
发布于 2014-12-06 21:02:02
根据jj__评论中的duplicate
function getGMapRandomColor() {
return 'hsla(' + Math.floor(Math.random()*360) + ', 100%, 70%, 1)';
} 发布于 2013-06-27 17:00:09
首先定义你想要的RGB范围,一旦你有了这些定义,只需在这些范围内生成随机值。或者定义你不想要的范围,继续循环,直到你找到一个符合这些标准的颜色,效率要低得多,但如果效率不是问题,编程就会容易得多。
https://stackoverflow.com/questions/17338762
复制相似问题