给定这个函数,我想用随机颜色生成器替换颜色。
document.overlay = GPolyline.fromEncoded({
color: "#0000FF",
weight: 10,
points: encoded_points,
zoomFactor: 32,
levels: encoded_levels,
numLevels: 4
});
我该怎么做呢?
给定这个函数,我想用随机颜色生成器替换颜色。
document.overlay = GPolyline.fromEncoded({
color: "#0000FF",
weight: 10,
points: encoded_points,
zoomFactor: 32,
levels: encoded_levels,
numLevels: 4
});
我该怎么做呢?
当前回答
这条线会为你随机改变颜色:
setInterval(function(){y.style.color=''+"rgb(1"+Math.floor(Math.random() * 100)+",1"+Math.floor(Math.random() * 100)+",1"+Math.floor(Math.random() * 100)+")"+'';},1000);
其他回答
下面是@Anatoliy提供的解决方案。
我只需要生成浅色(作为背景),所以我使用了三个字母(#AAA)格式:
function get_random_color() {
var letters = 'ABCDE'.split('');
var color = '#';
for (var i=0; i<3; i++ ) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
}
我想创造非常独特和充满活力的颜色(用于绘图)。对于任何严重的问题,hsl是一个比rgb更好的方法。如有必要,您可以像其他人已经提到的那样将hsl转换为rgb。
简单的方法:
创建一个从0到360的随机色调 创建一个从0.5到1(或50到100)的随机饱和度 将亮度设置为50%以获得最佳能见度。
color_generator = () => hsl (360*Math.random(), 0.5 + Math.random()/2, 0.5)
修改方法
它创造了一个非常明亮和生动的颜色光谱,但问题是,在通常的颜色光谱中,红色、绿色、蓝色比黄色、青色和紫色更占主导地位。我通过acos函数变换了色调。技术原因很无聊,所以我跳过了,但你可以在维基上挖掘。
color_generator = () => {
let color_section = Math.floor(Math.random()/0.33) // there are three section in full spectrum
let transformed_hue = Math.acos(2*Math.random() - 1)/3.14 // transform so secondary colors would be as dominant as the primary colors
let hue = 120*color_section + 120*transformed_hue
return hsl(hue, 0.5 + Math.random()/2, 0.5)
}
在尝试了许多其他方法后,这是我得到的最好的色谱。
引用:
https://observablehq.com/@d3/color-schemes https://en.wikipedia.org/wiki/HSL_and_HSV
您还可以使用在所有优秀浏览器(http://caniuse.com/#feat=css3-colors)上可用的HSL。
function randomHsl() {
return 'hsla(' + (Math.random() * 360) + ', 100%, 50%, 1)';
}
这将给你只有明亮的颜色,你可以玩亮度,饱和度和阿尔法。
// es6
const randomHsl = () => `hsla(${Math.random() * 360}, 100%, 50%, 1)`
我怀疑还有什么能比这条更快或更短:
"#" + ((1 << 24) * Math.random() | 0).toString(16).padStart(6, "0")
挑战!
Array.prototype.reduce使它非常简洁。
["r", "g", "b"].reduce(function(res) {
return res + ("0" + ~~(Math.random()*256).toString(16)).slice(-2)
}, "#")
它需要一个旧浏览器的垫片。