给定这个函数,我想用随机颜色生成器替换颜色。
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
});
我该怎么做呢?
当前回答
使用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);
}
其他回答
我喜欢这个:'#' + (Math.random().toString(16) + "000000").substring(2,8)
这个只生成饱和色
let randomSaturatedColor = () => {
let r = Math.random().toString(16).slice(2, 4)
let value_012345 = Math.random().toString(6).slice(2, 3)
let hex = {
[0]: `${r}00FF`,
[1]: `00${r}FF`,
[2]: `00FF${r}`,
[3]: `${r}FF00`,
[4]: `FF${r}00`,
[5]: `FF00${r}`,
}[value_012345]
return '#' + hex
}
var color = "#";
for (k = 0; k < 3; k++) {
color += ("0" + (Math.random()*256|0).toString(16)).substr(-2);
}
它是如何工作的:
Math.random()*256获取一个从0到256(包括0到255)的随机(浮点数)数字 示例结果:116.15200161933899
加上|0就把小数点后的数都去掉了。 例:116.15200161933899 -> 116
使用. tostring(16)将此数字转换为十六进制(以16为基数)。 例:116 -> 74 另一个例子:228 -> e4
加上“0”,它就变成了零。这在我们获取子字符串时很重要,因为我们的最终结果每种颜色必须有两个字符。 例:74 -> 074 另一个例子:8 -> 08
.substr(-2)只获取最后两个字符。 例:074 -> 74 另一个例子:08 -> 08(如果我们没有添加“0”,这将产生“8”而不是“08”)
for循环运行此循环三次,将每个结果添加到颜色字符串中,产生如下内容: # 7408 e4
增强了一点的一行代码,使方法更加生动
'#' + Math.round((0x1000000 + 0xffffff * Math.random())).toString(16).slice(1)
map
总是返回一个有效的RGB颜色:
`rgb(${[1,2,3].map(x=>Math.random()*256|0)})`
让c =“rgb ($ {[1, 2, 3] . map (x = > math . random() * 256 | 0)})” console.log (c); document.body.style.background = c