Generate Random Color distinguishable to Humans

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

Leave a Comment