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

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

我该怎么做呢?


当前回答

你可以用这个简单的函数

function getRandomColor(){
 var color =  "#" + (Math.random() * 0xFFFFFF << 0).toString(16);
 return color;
}

其他回答

这段代码(Mohsen的)不能生成像#fcfc80这样的颜色。

'#' + Math.random().toString(16).substr(-6);

Nicolas Buduroi的方法有效,除非Math.random()返回0,合理。

'#' + (Math.random().toString(16) + "000000").substring(2,8)

这段代码生成了很多非法的颜色(比如#abcde)。

'#' + Math.floor(Math.random()*16777215).toString(16);

我一直在用(+1或其他也可以,但我习惯了毫无理由的+2)

"#" + ((Math.random()+2)*16777216|0).toString(16).slice(1)

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;
}

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

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

没有必要使用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样本。

在这种情况下,我喜欢parseInt:

parseInt(Math.random()*0xFFFFFFFF).toString(16)