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

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

我该怎么做呢?


当前回答

var color = "#";
for (k = 0; k < 3; k++) {
    color += ("0" + (Math.random()*256|0).toString(16)).substr(-2);
}

它是如何工作的:

Math.random()*256获取一个从0到256(包括0到255)的随机(浮点数)数字 示例结果:116.15200161933899

加上|0就把小数点后的数都去掉了。 例:116.15200161933899 -> 116

使用. tostring(16)将此数字转换为十六进制(以16为基数)。 例:116 -> 74 另一个例子:228 -> e4

加上“0”,它就变成了零。这在我们获取子字符串时很重要,因为我们的最终结果每种颜色必须有两个字符。 例:74 -> 074 另一个例子:8 -> 08

.substr(-2)只获取最后两个字符。 例:074 -> 74 另一个例子:08 -> 08(如果我们没有添加“0”,这将产生“8”而不是“08”)

for循环运行此循环三次,将每个结果添加到颜色字符串中,产生如下内容: # 7408 e4

其他回答

使用ES6的Array.from()方法,我创建了这个解决方案:

function randomColor() {
  return "#"+ Array.from({length: 6},()=> Math.floor(Math.random()*16).toString(16)).join("");
}

我见过的其他实现需要确保如果十六进制值有前导零,则该数字仍然包含六位数字。

K._的回答使用了ES6的padStart:

function randomColor() {
  return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, 0)}`
}

我见过的另一个好的单线解决方案是

function randomColor() {
  return '#'+ ('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6);
}

你可以试试这个。这是一个绝对随机和舒适的颜色生成器))

var Color = '#';
var myElement;
for (var i = 0; i < 6; i++) {
    function Random1(from, to) {
      return Math.floor((Math.random() * (70 - 65 + 1)) + 65);
}
    function Random2(from, to) {
      return Math.floor((Math.random() * (1 - 0 + 1)) + 0);
}
    function Random3(from, to) {
      return Math.floor((Math.random() * (9 - 0 + 1)) + 0);
}
if (Random2()) {
     myElement = Random3();
}
else {
     myElement = String.fromCharCode(Random1());
}
Color += myElement;
}

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


/* 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))

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

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(",") + ")";
}

我的版本:

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