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

document.overlay = GPolyline.fromEncoded({
    color: "#0000FF",
    weight: 10,
    points: encoded_points,
    zoomFactor: 32,
    levels: encoded_levels,
    numLevels: 4
});

我该怎么做呢?


当前回答

'#'+Math.random().toString(16).slice(-3) // three-numbers format aka #f3c
'#'+Math.random().toString(16).slice(-6) // six-number format aka #abc123

其他回答

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;
}

你可以用这个简单的函数

function getRandomColor(){
 var color =  "#" + (Math.random() * 0xFFFFFF << 0).toString(16);
 return color;
}

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