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

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

我该怎么做呢?


当前回答

我认为第一个回答是最简洁/有用的,但我只是写了一个初学者可能更容易理解的回答。

function randomHexColor(){
    var hexColor=[]; //new Array()
    hexColor[0] = "#"; //first value of array needs to be hash tag for hex color val, could also prepend this later

    for (i = 1; i < 7; i++)
    {
        var x = Math.floor((Math.random()*16)); //Tricky: Hex has 16 numbers, but 0 is one of them

        if (x >=10 && x <= 15) //hex:0123456789ABCDEF, this takes care of last 6 
        {
            switch(x)
            {
                case 10: x="a" 
                break;
                case 11: x="b" 
                break;
                case 12: x="c" 
                break;
                case 13: x="d" 
                break;
                case 14: x="e" 
                break;
                case 15: x="f" 
                break;  
            }
        }
        hexColor[i] = x;
    }
    var cString = hexColor.join(""); //this argument for join method ensures there will be no separation with a comma
    return cString;
}

其他回答

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

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

挑战!

JS中的随机rgb颜色

const getRandomArbitrary = (min, max) => parseInt(Math.random() * (max - min) + min, 10)

const generateRandomRGBColor = () => 
    `rgb(${getRandomArbitrary(0, 255)}, ${getRandomArbitrary(0, 255)}, ${getRandomArbitrary(0, 255)})`;

// generateRandomRGBColor()

或者你可以使用在线工具来生成调色板-我已经为此目的建立了https://colorswall.com/palette/generate。

几乎所有以前的速记方法都会生成无效的十六进制代码(五位数)。我在这里遇到了一个类似的技巧,只是没有这个问题:

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

Test

在控制台试试这个:

for(i = 0; i < 200; i++) {
    console.log("#"+(((1+Math.random())*(1<<24)|0).toString(16)).substr(-6));
}

此方法将获得一个随机数,将其转换为十六进制字符串,然后提取它的一部分,从而得到一个随机十六进制。

function randomColor() {
    return "#" + Math.random().toString(16).slice(2,8);
}

这条线会为你随机改变颜色:

setInterval(function(){y.style.color=''+"rgb(1"+Math.floor(Math.random() * 100)+",1"+Math.floor(Math.random() * 100)+",1"+Math.floor(Math.random() * 100)+")"+'';},1000);