给定这个函数,我想用随机颜色生成器替换颜色。
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 r() {
return Math.floor(Math.random() * 256);
}
const color = "rgb(" + r() + "," + r() + "," + r() + ")";
你只需要以一个字符串结束,比如“rgb(255, 123, 220)”。
其他回答
你应该使用'#'+Math.floor(Math.random()*16777215).toString(16);对于一个随机的颜色代码。
你的想法,但为什么是16777215?检查本文:用一行JavaScript代码生成一种随机颜色
generateRandomColor()函数 { var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16); 如果(randomColor。length != 7){//在任何情况下,颜色代码都是无效的 randomColor = generateRandomColor(); } 返回randomColor; //随机的颜色将是新鲜的 } document.body.style.backgroundColor = generateRandomColor() // -> #E1AC94
这段代码(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)
使用相同的“随机”颜色,而不是使用数学。随机你可以使用,例如,Mulberry32算法。
下面是使用mulberry32打印随机颜色的行,它使用输入元素的种子值。
为了获得一个随机的颜色值,我使用HLS“生成器”。除了随机的“H”(色调)值(总共360种颜色)外,还使用随机的“L”(亮度)值(从“40%”到“60%”)。另外,每个下一个“H”值至少相差10,以防止相邻颜色过于相似。
function hlsGen(seed) { if (isNaN(seed)) { seed = 0; } const random = mulberry32(seed); let preH = 0; function getH() { while (true) { const newH = random() * 360; if (Math.abs(preH - newH) > 10) { preH = newH; return newH; } } } return function() { const H = getH(); const L = (40 + random() * 20) + "%"; return `hsl(${H}, 100%, ${L})`; }; } function mulberry32(seed = Date.now()) { return function() { let x = seed += 0x6D2B79F5; x = Math.imul(x ^ x >>> 15, x | 1); x ^= x + Math.imul(x ^ x >>> 7, x | 61); return ((x ^ x >>> 14) >>> 0) / 4294967296; } } // --- The example code --- const input = document.createElement("input"); document.body.append(input); input.addEventListener("input", () => { const seed = Number(input.value); const nextHls = hlsGen(seed); document.querySelectorAll("div").forEach(div => div.remove()); for (let i = 0; i < 20; i++) { const style = `border-left: 10px solid ${nextHls()};`; document.body.insertAdjacentHTML("beforeend", `<div style="${style}">${i}</div>`); } }); input.value = 100; input.dispatchEvent(new Event("input"));
function getRandomColor()
{
var color = "#";
for (var i = 0; i < 3; i++)
{
var part = Math.round(Math.random() * 255).toString(16);
color += (part.length > 1) ? part : "0" + part;
}
return color;
}
递归:
var randomColor = (s='') => s.length === 6 ? '#' + s : randomColor(s + '0123456789ABCDEF'[Math.floor(Math.random() * 16)]);
randomColor();