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

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

我该怎么做呢?


当前回答

为了适当的随机性。

随机的颜色

`#${crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, 0).slice(-6)}`

随机的阿尔法,随机的颜色。

`#${crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, 0)}`

其他回答

我的版本:

function RandomColor() {
  var hex = (Math.round(Math.random()*0xffffff)).toString(16);
  while (hex.length < 6) hex = "0" + hex;
  return hex;
}

审查

这里的许多答案都是基于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 getRandomColor(){
 var color =  "#" + (Math.random() * 0xFFFFFF << 0).toString(16);
 return color;
}

一个工作的单行解决方案(前导零填充):

var color = "#" + "colors".split("").map(function(){return parseInt(Math.random()*0x10).toString(16);}).join("");

函数 getHashColor() { var hash = “0123456789ABCDEF”; var hashColor = “#”; for (var i = 0; i < 6; i++) hashColor += hash[Math.floor(Math.random() * hash.length)]; document.getElementById('demo').style.background = hashColor } <div id=“demo” style=“background:red;height:300px;width:300px”></div> <button type=“button” onclick=“getHashColor()”>Clik Me</button>