I am trying to randomly generate a color in hex in javascript.
However the colors generated are almost indistinguishable from eachother.
Is there a way to improv
For randomly generating colors, I tend to go for something simple like this:
function randomColor () {
var max = 0xffffff;
return '#' + Math.round( Math.random() * max ).toString( 16 );
}
I'm not sure what you mean by unrecognizable. This method doesn't offer much customization, but at very least makes it easy to keep numbers from being too light or too dark.
If you want to give bigger gaps between the generated colors, you could try reducing the number of allowed characters. I've used a method like that in the past where I only used 0369cf
as the pool of characters to pull from. Combining this with a check for duplicates tends to give more distinguishable colors, as well as only utilizing the #fff
3-character syntax.
Here's your original function modified to use this method:
function randomColor(){
var allowed = "0369cf".split( '' ), s = "#";
while ( s.length < 4 ) {
s += allowed.splice( Math.floor( ( Math.random() * allowed.length ) ), 1 );
}
return s;
}