Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
482 views
in Technique[技术] by (71.8m points)

javascript - Generate Random Color distinguishable to Humans

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 improve it?


Here is the code I am using:

function randomColor(){
   var allowed = "ABCDEF0123456789", S = "#";

   while(S.length < 7){
       S += allowed.charAt(Math.floor((Math.random()*16)+1));
   }
   return S;
}

I heard something about HSL and HSV color model but can't get it to work in my code. Please help.

Thanks in Advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...