给定这个函数,我想用随机颜色生成器替换颜色。
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
});
我该怎么做呢?
当前回答
map
总是返回一个有效的RGB颜色:
`rgb(${[1,2,3].map(x=>Math.random()*256|0)})`
让c =“rgb ($ {[1, 2, 3] . map (x = > math . random() * 256 | 0)})” console.log (c); document.body.style.background = c
其他回答
我认为第一个回答是最简洁/有用的,但我只是写了一个初学者可能更容易理解的回答。
function randomHexColor(){
var hexColor=[]; //new Array()
hexColor[0] = "#"; //first value of array needs to be hash tag for hex color val, could also prepend this later
for (i = 1; i < 7; i++)
{
var x = Math.floor((Math.random()*16)); //Tricky: Hex has 16 numbers, but 0 is one of them
if (x >=10 && x <= 15) //hex:0123456789ABCDEF, this takes care of last 6
{
switch(x)
{
case 10: x="a"
break;
case 11: x="b"
break;
case 12: x="c"
break;
case 13: x="d"
break;
case 14: x="e"
break;
case 15: x="f"
break;
}
}
hexColor[i] = x;
}
var cString = hexColor.join(""); //this argument for join method ensures there will be no separation with a comma
return cString;
}
我怀疑还有什么能比这条更快或更短:
"#" + ((1 << 24) * Math.random() | 0).toString(16).padStart(6, "0")
挑战!
这是我的两个版本的随机十六进制代码生成器。
/* Slowest but shortest. */
"#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});
/* Good performance with small size. */
"#"+(function(a,b){while(a--){b+=""+(~~(Math.random()*16)).toString(16);} return b;})(6,"");
/* Remy Sharp provided one that's the fastest but a little bit too long */
(function(h){return '#000000'.substr(0,7-h.length)+h})((~~(Math.random()*(1<<24))).toString(16))
只是因为我可以,我创建了一个不可读的片段,在最小和最大十六进制代码之间随机…:
function a(f, s){
if(!s || !s.length > 1) return "";
var c = Math.floor(Math.random()*(parseInt("0x" + s.substr(0,2))-parseInt("0x" + f.substr(0,2))+1)+parseInt("0x" + f.substr(0,2))).toString(16);
return (Array(3 - c.length).join("0")) + c + a(f.substr(2,f.length),s.substr(2,s.length));
}
A ("990099","ff00ff")→可能随机化→b5009e
它是成对的,a("12","f2")→可能随机化→8f。 但它不会超过f2。
var color = "#" + a("11","22") + a("33","44") + a("55","66");
即:
var color = "#" + a("113355","224466")
但速度较慢。
我的版本:
function RandomColor() {
var hex = (Math.round(Math.random()*0xffffff)).toString(16);
while (hex.length < 6) hex = "0" + hex;
return hex;
}