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
First of all, why are you building hex values from strings? Just use numbers for the values, then output with something like yourNumber.toString(16)
.
Then, to make the colours more distinct, don't use the full range of 0 to 255 for each colour component, but maybe go in jumps of 10, or 20, or whatever you need to generate wide enough differences.
The easiest way to pick maximally different colors would be to to use HSL values instead of RGB and then manipulate Hue, as it has a value from 0 to 360 value and wraps around (0 is red, and so is 360);
if you need 10 distinguishable colors you can divide 360 by 10 and then pick the individual color by multiplying the value by index (zero based). Here's an example function that allows you to pick a color from :
function selectColor(colorNum, colors){
if (colors < 1) colors = 1; // defaults to one color - avoid divide by zero
return "hsl(" + (colorNum * (360 / colors) % 360) + ",100%,50%)";
}
This way you can randomize the color selection by randomizing index, but colors will always be in the same palette.
This will select a random color from a palette of 10:
var color = selectColor(Math.floor(Math.random() * 10), 10);
and so will this:
var color = selectColor(Math.floor(Math.random() * 999), 10);
or you can select a specific color from the palette, like 9th color (index 8) out of palette of 13:
var color = selectColor(8, 13);
Here's a fiddle to play with: http://jsfiddle.net/2UE2B/
Update on 2020-02-23:
So, today I needed a solution to this same problem. Googling for this answer here (I know, a very weird way to look for stuff on SO) I ran into the Golden Angle concept. It would make the above example even more trivial, and would not require a predetermined number of colors to be provided:
function selectColor(number) {
const hue = number * 137.508; // use golden angle approximation
return `hsl(${hue},50%,75%)`;
}
This answers the @netoperator-wibby's question
I wrote up a small script called SwitchColors.js which can be found here: https://github.com/akulmehta/SwitchColors.js
The script produces more saturated colors and the brightness can be controlled. Although it may not produce visually distinguishable colors, it produces high saturation and bright colors which can also be attractive.