给定这个函数,我想用随机颜色生成器替换颜色。

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

其他回答

我怀疑还有什么能比这条更快或更短:

"#" + ((1 << 24) * Math.random() | 0).toString(16).padStart(6, "0")

挑战!

function generateRandomColor()
{
    var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
    return randomColor;
    //random color will be freshly served
}
document.body.style.backgroundColor = generateRandomColor() // -> #e1ac94
someDiv.style.color = generateRandomColor() // -> #34c7aa

使用ES6的Array.from()方法,我创建了这个解决方案:

function randomColor() {
  return "#"+ Array.from({length: 6},()=> Math.floor(Math.random()*16).toString(16)).join("");
}

我见过的其他实现需要确保如果十六进制值有前导零,则该数字仍然包含六位数字。

K._的回答使用了ES6的padStart:

function randomColor() {
  return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, 0)}`
}

我见过的另一个好的单线解决方案是

function randomColor() {
  return '#'+ ('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6);
}

使用相同的“随机”颜色,而不是使用数学。随机你可以使用,例如,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"));

有多种方法来创建随机十六进制颜色代码在博客文章中随机十六进制颜色代码生成器在JavaScript。当随机值小于0×100000时,你需要用0填充,所以下面是正确的版本:

var randomColor = "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});

这将用一个随机的十六进制数字替换六个0中的每一个,因此它一定会得到一个完整的六位数有效颜色值。