给定这个函数,我想用随机颜色生成器替换颜色。
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
});
我该怎么做呢?
当前回答
随机颜色生成与亮度控制:
function getRandColor(brightness){
// Six levels of brightness from 0 to 5, 0 being the darkest
var rgb = [Math.random() * 256, Math.random() * 256, Math.random() * 256];
var mix = [brightness*51, brightness*51, brightness*51]; //51 => 255/5
var mixedrgb = [rgb[0] + mix[0], rgb[1] + mix[1], rgb[2] + mix[2]].map(function(x){ return Math.round(x/2.0)})
return "rgb(" + mixedrgb.join(",") + ")";
}
其他回答
你可以用这个简单的函数
function getRandomColor(){
var color = "#" + (Math.random() * 0xFFFFFF << 0).toString(16);
return color;
}
这条线会为你随机改变颜色:
setInterval(function(){y.style.color=''+"rgb(1"+Math.floor(Math.random() * 100)+",1"+Math.floor(Math.random() * 100)+",1"+Math.floor(Math.random() * 100)+")"+'';},1000);
创建一个基于任意随机值的唯一颜色
selectColor(numberOrString) {
if (typeof numberOrString === "string") {
// convert string to number
numberOrString = numberOrString.toLowerCase().split('').reduce(function (a, b) {
a = ((a << 5) - a) + b.charCodeAt(0); // explained here: https://stackoverflow.com/a/7616484/112731
return a & a
}, 0);
}
const hue = numberOrString * 137.508; // use golden angle approximation
return `hsl(${hue},50%,75%)`;
}
许多答案调用Math.random()的次数比必需的要多。或者他们希望这个数字的十六进制表示,有六个字符。
首先将随机浮点数乘以范围[0,0xffffff + 1)。现在我们的数字有了0xRRRRRR的形式和一些变化,这是一个有24位有效位的数字。一次读取4位,并使用该随机数[0,15]并在查找时将其转换为匹配的十六进制字符。
function randomColor() {
var lookup = "0123456789abcdef";
var seed = Math.random() * 0x1000000;
return (
"#" +
lookup[(seed & 0xf00000) >> 20] +
lookup[(seed & 0x0f0000) >> 16] +
lookup[(seed & 0x00f000) >> 12] +
lookup[(seed & 0x000f00) >> 8] +
lookup[(seed & 0x0000f0) >> 4] +
lookup[seed & 0x00000f]
);
};
这是我的两个版本的随机十六进制代码生成器。
/* 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))