给定这个函数,我想用随机颜色生成器替换颜色。
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
});
我该怎么做呢?
当前回答
只是因为我可以,我创建了一个不可读的片段,在最小和最大十六进制代码之间随机…:
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;
}
Array.prototype.reduce使它非常简洁。
["r", "g", "b"].reduce(function(res) {
return res + ("0" + ~~(Math.random()*256).toString(16)).slice(-2)
}, "#")
它需要一个旧浏览器的垫片。
这是我的两个版本的随机十六进制代码生成器。
/* 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))
这段代码(Mohsen的)不能生成像#fcfc80这样的颜色。
'#' + Math.random().toString(16).substr(-6);
Nicolas Buduroi的方法有效,除非Math.random()返回0,合理。
'#' + (Math.random().toString(16) + "000000").substring(2,8)
这段代码生成了很多非法的颜色(比如#abcde)。
'#' + Math.floor(Math.random()*16777215).toString(16);
我一直在用(+1或其他也可以,但我习惯了毫无理由的+2)
"#" + ((Math.random()+2)*16777216|0).toString(16).slice(1)
function randomColor(format = 'hex') {
const rnd = Math.random().toString(16).slice(-6);
if (format === 'hex') {
return '#' + rnd;
}
if (format === 'rgb') {
const [r, g, b] = rnd.match(/.{2}/g).map(c=>parseInt(c, 16));
return `rgb(${r}, ${g}, ${b})`;
}
}