给定这个函数,我想用随机颜色生成器替换颜色。
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 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;
}
其他回答
创建一个基于任意随机值的唯一颜色
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%)`;
}
不需要十六进制字母的散列。JavaScript可以自己做到这一点:
function get_random_color() {
function c() {
var hex = Math.floor(Math.random()*256).toString(16);
return ("0"+String(hex)).substr(-2); // pad with zero
}
return "#"+c()+c()+c();
}
有多种方法来创建随机十六进制颜色代码在博客文章中随机十六进制颜色代码生成器在JavaScript。当随机值小于0×100000时,你需要用0填充,所以下面是正确的版本:
var randomColor = "#000000".replace(/0/g,function(){return (~~(Math.random()*16)).toString(16);});
这将用一个随机的十六进制数字替换六个0中的每一个,因此它一定会得到一个完整的六位数有效颜色值。
函数 getHashColor() { var hash = “0123456789ABCDEF”; var hashColor = “#”; for (var i = 0; i < 6; i++) hashColor += hash[Math.floor(Math.random() * hash.length)]; document.getElementById('demo').style.background = hashColor } <div id=“demo” style=“background:red;height:300px;width:300px”></div> <button type=“button” onclick=“getHashColor()”>Clik Me</button>
你可以用这个简单的函数
function getRandomColor(){
var color = "#" + (Math.random() * 0xFFFFFF << 0).toString(16);
return color;
}