给定这个函数,我想用随机颜色生成器替换颜色。
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
});
我该怎么做呢?
当前回答
在这种情况下,我喜欢parseInt:
parseInt(Math.random()*0xFFFFFFFF).toString(16)
其他回答
增强了一点的一行代码,使方法更加生动
'#' + Math.round((0x1000000 + 0xffffff * Math.random())).toString(16).slice(1)
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
var html = '';
var red;
var green;
var blue;
var rgbColor;
for ( var i = 1; i <= 100; i += 1) {
red = Math.floor(Math.random() * 256 );
green = Math.floor(Math.random() * 256 );
blue = Math.floor(Math.random() * 256 );
rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
html += '<div style="background-color:' + rgbColor + '"></div>';
}
document.write(html);
不需要十六进制字母的散列。JavaScript可以自己做到这一点:
function get_random_color() {
function c() {
var hex = Math.floor(Math.random()*256).toString(16);
return ("0"+String(hex)).substr(-2); // pad with zero
}
return "#"+c()+c()+c();
}
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})`;
}
}