给定这个函数,我想用随机颜色生成器替换颜色。
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
});
我该怎么做呢?
当前回答
为了适当的随机性。
随机的颜色
`#${crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, 0).slice(-6)}`
随机的阿尔法,随机的颜色。
`#${crypto.getRandomValues(new Uint32Array(1))[0].toString(16).padStart(8, 0)}`
其他回答
Use:
function random_color(format)
{
var rint = Math.round(0xffffff * Math.random());
switch(format)
{
case 'hex':
return ('#0' + rint.toString(16)).replace(/^#0([0-9a-f]{6})$/i, '#$1');
break;
case 'rgb':
return 'rgb(' + (rint >> 16) + ',' + (rint >> 8 & 255) + ',' + (rint & 255) + ')';
break;
default:
return rint;
break;
}
}
升级版:
function random_color( format ){
var rint = Math.floor( 0x100000000 * Math.random());
switch( format ){
case 'hex':
return '#' + ('00000' + rint.toString(16)).slice(-6).toUpperCase();
case 'hexa':
return '#' + ('0000000' + rint.toString(16)).slice(-8).toUpperCase();
case 'rgb':
return 'rgb(' + (rint & 255) + ',' + (rint >> 8 & 255) + ',' + (rint >> 16 & 255) + ')';
case 'rgba':
return 'rgba(' + (rint & 255) + ',' + (rint >> 8 & 255) + ',' + (rint >> 16 & 255) + ',' + (rint >> 24 & 255)/255 + ')';
default:
return rint;
}
}
审查
这里的许多答案都是基于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和十六进制,所以在这个答案中,我不会提出另一个解决方案。
试试这个包- https://www.npmjs.com/package/gen-random-colors。
它还提供了从0到5(0是最暗的)配置颜色集的能力。
function randomColor(format = 'hex') {
const rnd = Math.random().toString(16).slice(-6);
if (format === 'hex') {
return '#' + rnd;
}
if (format === 'rgb') {
const [r, g, b] = rnd.match(/.{2}/g).map(c=>parseInt(c, 16));
return `rgb(${r}, ${g}, ${b})`;
}
}
正则表达式
总是返回有效的十六进制6位颜色
"#xxxxxx".replace(/x/g, y=>(Math.random()*16|0).toString(16))
令c= "#xxxxxx"。替换(/ x / g, y = > (math . random () * 16 | 0) .toString (16)); console.log (c); document.body.style.background = c