What is the best way to generate a random color in JavaScript Without using any frameworks...
Here are a couple of solutions I came up with:
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;
}
Are there better ways to do it?
I like your second option, although it can be made a little bit simpler:
Most succinct:
Nicolas Buduroi gave the above best code to get random color at Random Color generator in Javascript
Here's a way to generate a random color and provide the minimum 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)
This returns a random RGB value.