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

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

我该怎么做呢?


当前回答

审查

这里的许多答案都是基于Math.random(). tostring(16)。他们有时会用一个随机数乘以一些数字,并假设转换到十六进制字符串总是会产生一个浮点十六进制表示,在点后面至少有6个数字(并且他们使用这些数字作为颜色)。

这是一个错误的假设

因为有很多数字实际上给出的数字小于6位(在点后面)。如果Math.random()选择这样一个数字,那么结果的十六进制颜色将无效(除非有人处理这种情况)。下面是一个生成器的例子(我是基于这个转换器编写的)。

function calc() { let n = hex2dec(hexInput.value) console.log(`${n} -> ${n.toString(16)}` ); } // Source: https://stackoverflow.com/questions/5055723/converting-hexadecimal-to-float-in-javascript/5055821#5055821 function hex2dec(hex) { hex = hex.split(/\./); var len = hex[1].length; hex[1] = parseInt(hex[1], 16); hex[1] *= Math.pow(16, -len); return parseInt(hex[0], 16) + hex[1]; } Put some 5-digit (or less) hexdecimal number in range 0-1<br> <input id="hexInput" value="0.2D4EE"> <button onclick="calc()">Calc</button>

我已经在没有这个假设的情况下对你的问题给出了两个答案:RGB和十六进制,所以在这个答案中,我不会提出另一个解决方案。

其他回答

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

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

你应该使用'#'+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

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

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

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

没有必要使用JavaScript来生成一个随机的CSS颜色。

例如,在SCSS/Sass中,你可以使用这样的东西:

.rgb-color-selector {
    background-color: rgb(random(255), random(255), random(255));
}

or

.hsl-color-selector {
    color: hsl(random(360) * 1deg, floor(random() * 100%), floor(random() * 100%));;
}

CodePen样本。