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

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

我该怎么做呢?


当前回答

随机颜色生成与亮度控制:

function getRandColor(brightness){

    // Six levels of brightness from 0 to 5, 0 being the darkest
    var rgb = [Math.random() * 256, Math.random() * 256, Math.random() * 256];
    var mix = [brightness*51, brightness*51, brightness*51]; //51 => 255/5
    var mixedrgb = [rgb[0] + mix[0], rgb[1] + mix[1], rgb[2] + mix[2]].map(function(x){ return Math.round(x/2.0)})
    return "rgb(" + mixedrgb.join(",") + ")";
}

其他回答

增强了一点的一行代码,使方法更加生动

'#' + Math.round((0x1000000 + 0xffffff * Math.random())).toString(16).slice(1)

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

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

正则表达式

总是返回有效的十六进制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

函数 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>

Use:

function randomColor(){
  var num = Math.round(Math.random() * Math.pow(10,7));
  // Converting number to hex string to be read as RGB
  var hexString = '#' + num.toString(16);

  return hexString;
}