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

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

我该怎么做呢?


当前回答

function get_random_color() {
    return "#" + (Math.round(Math.random() * 0XFFFFFF)).toString(16);
}

http://jsfiddle.net/XmqDz/1/

其他回答

创建一个基于任意随机值的唯一颜色

    selectColor(numberOrString) {
      if (typeof numberOrString === "string") {
        // convert string to number
        numberOrString = numberOrString.toLowerCase().split('').reduce(function (a, b) {
          a = ((a << 5) - a) + b.charCodeAt(0); // explained here: https://stackoverflow.com/a/7616484/112731
          return a & a
        }, 0);
      }
      const hue = numberOrString * 137.508; // use golden angle approximation
      return `hsl(${hue},50%,75%)`;
    }

Paul Irish写的文章《JavaScript中的随机十六进制颜色代码生成器》绝对令人惊叹。使用:

'#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');

感谢Haytam分享padStart来解决十六进制代码长度的问题。

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

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.random().toString(16).slice(-3) // three-numbers format aka #f3c
'#'+Math.random().toString(16).slice(-6) // six-number format aka #abc123

不需要十六进制字母的散列。JavaScript可以自己做到这一点:

function get_random_color() {
  function c() {
    var hex = Math.floor(Math.random()*256).toString(16);
    return ("0"+String(hex)).substr(-2); // pad with zero
  }
  return "#"+c()+c()+c();
}