给定这个函数,我想用随机颜色生成器替换颜色。
document.overlay = GPolyline.fromEncoded({
color: "#0000FF",
weight: 10,
points: encoded_points,
zoomFactor: 32,
levels: encoded_levels,
numLevels: 4
});
我该怎么做呢?
给定这个函数,我想用随机颜色生成器替换颜色。
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();
其他回答
递归:
var randomColor = (s='') => s.length === 6 ? '#' + s : randomColor(s + '0123456789ABCDEF'[Math.floor(Math.random() * 16)]);
randomColor();
我的版本:
function RandomColor() {
var hex = (Math.round(Math.random()*0xffffff)).toString(16);
while (hex.length < 6) hex = "0" + hex;
return hex;
}
我认为第一个回答是最简洁/有用的,但我只是写了一个初学者可能更容易理解的回答。
function randomHexColor(){
var hexColor=[]; //new Array()
hexColor[0] = "#"; //first value of array needs to be hash tag for hex color val, could also prepend this later
for (i = 1; i < 7; i++)
{
var x = Math.floor((Math.random()*16)); //Tricky: Hex has 16 numbers, but 0 is one of them
if (x >=10 && x <= 15) //hex:0123456789ABCDEF, this takes care of last 6
{
switch(x)
{
case 10: x="a"
break;
case 11: x="b"
break;
case 12: x="c"
break;
case 13: x="d"
break;
case 14: x="e"
break;
case 15: x="f"
break;
}
}
hexColor[i] = x;
}
var cString = hexColor.join(""); //this argument for join method ensures there will be no separation with a comma
return cString;
}
所以,虽然这里所有的答案都很好,但我想对输出有更多的控制。例如,我想防止任何接近白色的阴影,同时确保我得到明亮的充满活力的颜色,而不是水洗阴影。
function generateColor(ranges) {
if (!ranges) {
ranges = [
[150,256],
[0, 190],
[0, 30]
];
}
var g = function() {
//select random range and remove
var range = ranges.splice(Math.floor(Math.random()*ranges.length), 1)[0];
//pick a random number from within the range
return Math.floor(Math.random() * (range[1] - range[0])) + range[0];
}
return "rgb(" + g() + "," + g() + "," + g() +")";
};
所以现在我可以指定3个任意范围来选择rgb值。你可以不带参数调用它,得到我的默认设置,它通常会生成一个非常鲜艳的颜色,有明显的主色调,或者你可以提供你自己的范围数组。
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);