给定这个函数,我想用随机颜色生成器替换颜色。
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
});
我该怎么做呢?
当前回答
函数 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>
其他回答
审查
这里的许多答案都是基于Math.random(). tostring(16)。他们有时会用一个随机数乘以一些数字,并假设转换到十六进制字符串总是会产生一个浮点十六进制表示,在点后面至少有6个数字(并且他们使用这些数字作为颜色)。
这是一个错误的假设
因为有很多数字实际上给出的数字小于6位(在点后面)。如果Math.random()选择这样一个数字,那么结果的十六进制颜色将无效(除非有人处理这种情况)。下面是一个生成器的例子(我是基于这个转换器编写的)。
function calc() { let n = hex2dec(hexInput.value) console.log(`${n} -> ${n.toString(16)}` ); } // Source: https://stackoverflow.com/questions/5055723/converting-hexadecimal-to-float-in-javascript/5055821#5055821 function hex2dec(hex) { hex = hex.split(/\./); var len = hex[1].length; hex[1] = parseInt(hex[1], 16); hex[1] *= Math.pow(16, -len); return parseInt(hex[0], 16) + hex[1]; } Put some 5-digit (or less) hexdecimal number in range 0-1<br> <input id="hexInput" value="0.2D4EE"> <button onclick="calc()">Calc</button>
我已经在没有这个假设的情况下对你的问题给出了两个答案:RGB和十六进制,所以在这个答案中,我不会提出另一个解决方案。
此方法将获得一个随机数,将其转换为十六进制字符串,然后提取它的一部分,从而得到一个随机十六进制。
function randomColor() {
return "#" + Math.random().toString(16).slice(2,8);
}
使用色彩分明的颜色。
它生成了一个视觉上不同颜色的调色板。
Distinct-colors是高度可配置的:
选择调色板中有多少种颜色 将色调限制在一个特定的范围内 限制色度(饱和度)到一个特定的范围 将亮度限制在一个特定的范围内 配置调色板的一般质量
我的版本:
function RandomColor() {
var hex = (Math.round(Math.random()*0xffffff)).toString(16);
while (hex.length < 6) hex = "0" + hex;
return hex;
}
下面是@Anatoliy提供的解决方案。
我只需要生成浅色(作为背景),所以我使用了三个字母(#AAA)格式:
function get_random_color() {
var letters = 'ABCDE'.split('');
var color = '#';
for (var i=0; i<3; i++ ) {
color += letters[Math.floor(Math.random() * letters.length)];
}
return color;
}