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?
A shorter way:
I have created a slightly more complicated solution but one which lets you control the saturation of the colors and the brightness. You can check out the code for SwitchColors.js here https://github.com/akulmehta/SwitchColors.js
This answer is the best method.
You should provide known colors to choose from instead of relying on purely numeric methods. You can use sites like ColorBrewer to choose color palettes that work well depending on the problem (qualitative dataset, quantitative, or whatever..)
['red','orange','yellow','green','blue','purple'][Math.random()*6|0]
More succinct:
As George said the best way is to use HSL, so you can generate a bunch of random human-distinguishable colours. The similar idea is implemented in Adams Cole answer to the similar question, but his code have random color generator and hsl->hex rgb translator bundled together which makes it hard to understand and modify.
If you use one of the javascript color manipulation libraries (like jquery-color) color generation become trivial:
I did it like this, with the help of other answers: