37 javascript random
在JavaScript中生成随机颜色的最佳方法是什么?不使用任何框架...
以下是我提出的几个解决方案:
function get_random_color()
{
var color = "";
for(var i = 0; i < 3; i++) {
var sub = Math.floor(Math.random() * 256).toString(16);
color += (sub.length == 1 ? "0" + sub : sub);
}
return "#" + color;
}
function get_rand_color()
{
var color = Math.floor(Math.random() * Math.pow(256, 3)).toString(16);
while(color.length < 6) {
color = "0" + color;
}
return "#" + color;
}
Run Code Online (Sandbox Code Playgroud)
有更好的方法吗?
Fra*_*ger 100
更短的方式:
'#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6)
Run Code Online (Sandbox Code Playgroud)
Bli*_*ixt 14
我喜欢你的第二种选择,虽然它可以更简单一些:
// Math.pow is slow, use constant instead.
var color = Math.floor(Math.random() * 16777216).toString(16);
// Avoid loops.
return '#000000'.slice(0, -color.length) + color;
Run Code Online (Sandbox Code Playgroud)
这是一种生成随机颜色并提供最小亮度的方法:
function randomColor(brightness){
function randomChannel(brightness){
var r = 255-brightness;
var n = 0|((Math.random() * r) + brightness);
var s = n.toString(16);
return (s.length==1) ? '0'+s : s;
}
return '#' + randomChannel(brightness) + randomChannel(brightness) + randomChannel(brightness);
}
Run Code Online (Sandbox Code Playgroud)
使用0-255的值调用randomColor,指示颜色应该有多亮.例如,这有助于生成粉彩randomColor(220)
正如乔治所说,最好的方法是使用HSL,这样你就可以产生一堆随机的人类可区分的颜色.类似的想法在Adams Cole中实现了对类似问题的回答,但是他的代码将随机颜色生成器和hsl-> hex rgb转换器捆绑在一起,这使得它很难理解和修改.
如果您使用其中一个javascript颜色操作库(如jquery-color)颜色生成变得微不足道:
function rainbow() {
// 30 random hues with step of 12 degrees
var hue = Math.floor(Math.random() * 30) * 12;
return $.Color({
hue: hue,
saturation: 0.9,
lightness: 0.6,
alpha: 1
}).toHexString();
};
Run Code Online (Sandbox Code Playgroud)
我在其他答案的帮助下做到了这一点:
'#' + parseInt(Math.random() * 0xffffff).toString(16)
Run Code Online (Sandbox Code Playgroud)
更简洁:
function get_random_color2()
{
var r = function () { return Math.floor(Math.random()*256) };
return "rgb(" + r() + "," + r() + "," + r() + ")";
}
Run Code Online (Sandbox Code Playgroud)