Best way to generate a random color in javascript? [closed]
Solution 1:
A shorter way:
'#'+(0x1000000+Math.random()*0xffffff).toString(16).substr(1,6)
Solution 2:
Here's a way to generate a random color and provide the minimum brightness:
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);
}
Call randomColor with a value from 0-255, indicitating how bright the color should be. This is helpful for generating pastels, for example randomColor(220)
Solution 3:
I like your second option, although it can be made a little bit simpler:
// 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;