给定这个函数,我想用随机颜色生成器替换颜色。
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
});
我该怎么做呢?
当前回答
用这个:
// RGBA()
function getRandomRGBA() {
function numbers() {
var x = Math.floor(Math.random() * 256);
return x;
}
alpha = 1.0;
return (
"rgba(" +
numbers() +
", " +
numbers() +
", " +
numbers() +
", " +
alpha.toFixed(1) +
")"
);
}
其他回答
使用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);
}
这是我的两个版本的随机十六进制代码生成器。
/* 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))
另一个随机颜色生成器:
var randomColor;
randomColor = Math.random() * 0x1000000; // 0 < randomColor < 0x1000000 (randomColor is a float)
randomColor = Math.floor(randomColor); // 0 < randomColor <= 0xFFFFFF (randomColor is an integer)
randomColor = randomColor.toString(16); // hex representation randomColor
randomColor = ("000000" + randomColor).slice(-6); // leading zeros added
randomColor = "#" + randomColor; // # added
您还可以使用在所有优秀浏览器(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);