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

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

我该怎么做呢?


当前回答

递归:

var randomColor = (s='') => s.length === 6 ? '#' + s : randomColor(s + '0123456789ABCDEF'[Math.floor(Math.random() * 16)]);
randomColor();

其他回答

你可以用这个简单的函数

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

下面是对这个问题的另一种看法。

我的目标是创造充满活力和独特的颜色。为了确保颜色的不同,我避免使用随机生成器,并从彩虹中选择“均匀间隔”的颜色。

这非常适合在谷歌map中创建具有最佳“唯一性”(即没有两个标记具有相似的颜色)的弹出式标记。

/**
 * @param numOfSteps: Total number steps to get color, means total colors
 * @param step: The step number, means the order of the color
 */
function rainbow(numOfSteps, step) {
    // This function generates vibrant, "evenly spaced" colours (i.e. no clustering). This is ideal for creating easily distinguishable vibrant markers in Google Maps and other apps.
    // Adam Cole, 2011-Sept-14
    // HSV to RBG adapted from: http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
    var r, g, b;
    var h = step / numOfSteps;
    var i = ~~(h * 6);
    var f = h * 6 - i;
    var q = 1 - f;
    switch(i % 6){
        case 0: r = 1; g = f; b = 0; break;
        case 1: r = q; g = 1; b = 0; break;
        case 2: r = 0; g = 1; b = f; break;
        case 3: r = 0; g = q; b = 1; break;
        case 4: r = f; g = 0; b = 1; break;
        case 5: r = 1; g = 0; b = q; break;
    }
    var c = "#" + ("00" + (~ ~(r * 255)).toString(16)).slice(-2) + ("00" + (~ ~(g * 255)).toString(16)).slice(-2) + ("00" + (~ ~(b * 255)).toString(16)).slice(-2);
    return (c);
}

如果您希望看到这看起来像在行动,请参阅简单JavaScript彩虹颜色生成器谷歌地图标记。

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

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

正则表达式

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

我的版本:

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