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

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

我该怎么做呢?


当前回答

Array.prototype.reduce使它非常简洁。

["r", "g", "b"].reduce(function(res) {
    return res + ("0" + ~~(Math.random()*256).toString(16)).slice(-2)
}, "#")

它需要一个旧浏览器的垫片。

其他回答

您还可以使用在所有优秀浏览器(http://caniuse.com/#feat=css3-colors)上可用的HSL。

function randomHsl() {
    return 'hsla(' + (Math.random() * 360) + ', 100%, 50%, 1)';
}

这将给你只有明亮的颜色,你可以玩亮度,饱和度和阿尔法。

// es6
const randomHsl = () => `hsla(${Math.random() * 360}, 100%, 50%, 1)`
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);

一个简短的答案,有精确大小的填充:

'#' + ((1<<24)*(Math.random()+1)|0).toString(16).substr(1)
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;
}

为了适当的随机性。

随机的颜色

`#${crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, 0).slice(-6)}`

随机的阿尔法,随机的颜色。

`#${crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, 0)}`