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

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

我该怎么做呢?


当前回答

我的版本:

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

其他回答

使用getRandomColor()代替“#0000FF”:

function getRandomColor() { var letters = '0123456789ABCDEF'; var color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; } function setRandomColor() { $("#colorpad").css("background-color", getRandomColor()); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="colorpad" style="width:300px;height:300px;background-color:#000"> </div> <button onclick="setRandomColor()">Random Color</button>

function getRandomColor()
{
    var color = "#";

    for (var i = 0; i < 3; i++)
    {
        var part = Math.round(Math.random() * 255).toString(16);

        color += (part.length > 1) ? part : "0" + part;
    }

    return color;
}

这是我的两个版本的随机十六进制代码生成器。


/* Slowest but shortest. */
"#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});    

/* Good performance with small size. */
"#"+(function(a,b){while(a--){b+=""+(~~(Math.random()*16)).toString(16);} return b;})(6,"");

/* Remy Sharp provided one that's the fastest but a little bit too long */
(function(h){return '#000000'.substr(0,7-h.length)+h})((~~(Math.random()*(1<<24))).toString(16))

var html = '';
var red;
var green;
var blue;
var rgbColor;

for ( var i = 1; i <= 100; i += 1) {
  red = Math.floor(Math.random() * 256 );
  green = Math.floor(Math.random() * 256 );
  blue = Math.floor(Math.random() * 256 );
  rgbColor = 'rgb(' + red + ',' + green + ',' + blue + ')';
  html += '<div style="background-color:' + rgbColor + '"></div>';  
}

document.write(html);

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

    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%)`;
    }