给定这个函数,我想用随机颜色生成器替换颜色。
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
});
我该怎么做呢?
当前回答
正则表达式
总是返回有效的十六进制6位颜色
"#xxxxxx".replace(/x/g, y=>(Math.random()*16|0).toString(16))
令c= "#xxxxxx"。替换(/ x / g, y = > (math . random () * 16 | 0) .toString (16)); console.log (c); document.body.style.background = c
其他回答
谁能打败它?
'#' + Math.random().toString(16).substr(-6);
它保证一直工作:http://jsbin.com/OjELIfo/2/edit
根据eterps的注释,如果随机颜色的十六进制表示非常短(0.730224609375 => 0.baf),上面的代码仍然可以生成更短的字符串。
这段代码应该在所有情况下工作:
function makeRandomColor(){
var c = '';
while (c.length < 7) {
c += (Math.random()).toString(16).substr(-6).substr(-1)
}
return '#' + c;
}
随机颜色生成与亮度控制:
function getRandColor(brightness){
// Six levels of brightness from 0 to 5, 0 being the darkest
var rgb = [Math.random() * 256, Math.random() * 256, Math.random() * 256];
var mix = [brightness*51, brightness*51, brightness*51]; //51 => 255/5
var mixedrgb = [rgb[0] + mix[0], rgb[1] + mix[1], rgb[2] + mix[2]].map(function(x){ return Math.round(x/2.0)})
return "rgb(" + mixedrgb.join(",") + ")";
}
另一个随机颜色生成器:
var randomColor;
randomColor = Math.random() * 0x1000000; // 0 < randomColor < 0x1000000 (randomColor is a float)
randomColor = Math.floor(randomColor); // 0 < randomColor <= 0xFFFFFF (randomColor is an integer)
randomColor = randomColor.toString(16); // hex representation randomColor
randomColor = ("000000" + randomColor).slice(-6); // leading zeros added
randomColor = "#" + randomColor; // # added
在这种情况下,我喜欢parseInt:
parseInt(Math.random()*0xFFFFFFFF).toString(16)
一个简短的答案,有精确大小的填充:
'#' + ((1<<24)*(Math.random()+1)|0).toString(16).substr(1)