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

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

我该怎么做呢?


当前回答

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

其他回答

你应该使用'#'+Math.floor(Math.random()*16777215).toString(16);对于一个随机的颜色代码。

你的想法,但为什么是16777215?检查本文:用一行JavaScript代码生成一种随机颜色

generateRandomColor()函数 { var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16); 如果(randomColor。length != 7){//在任何情况下,颜色代码都是无效的 randomColor = generateRandomColor(); } 返回randomColor; //随机的颜色将是新鲜的 } document.body.style.backgroundColor = generateRandomColor() // -> #E1AC94

您还可以使用在所有优秀浏览器(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)`
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;
}

审查

这里的许多答案都是基于Math.random(). tostring(16)。他们有时会用一个随机数乘以一些数字,并假设转换到十六进制字符串总是会产生一个浮点十六进制表示,在点后面至少有6个数字(并且他们使用这些数字作为颜色)。

这是一个错误的假设

因为有很多数字实际上给出的数字小于6位(在点后面)。如果Math.random()选择这样一个数字,那么结果的十六进制颜色将无效(除非有人处理这种情况)。下面是一个生成器的例子(我是基于这个转换器编写的)。

function calc() { let n = hex2dec(hexInput.value) console.log(`${n} -> ${n.toString(16)}` ); } // Source: https://stackoverflow.com/questions/5055723/converting-hexadecimal-to-float-in-javascript/5055821#5055821 function hex2dec(hex) { hex = hex.split(/\./); var len = hex[1].length; hex[1] = parseInt(hex[1], 16); hex[1] *= Math.pow(16, -len); return parseInt(hex[0], 16) + hex[1]; } Put some 5-digit (or less) hexdecimal number in range 0-1<br> <input id="hexInput" value="0.2D4EE"> <button onclick="calc()">Calc</button>

我已经在没有这个假设的情况下对你的问题给出了两个答案:RGB和十六进制,所以在这个答案中,我不会提出另一个解决方案。

'#'+Math.random().toString(16).slice(-3) // three-numbers format aka #f3c
'#'+Math.random().toString(16).slice(-6) // six-number format aka #abc123