I was trying to generate some random numbers for the Markers on the map:
The colours need to be diverse for each travel pairs for easy distinction, and cannot be too light.
I want to use an array of three numbers so that I’ll have the flexibility to use rgba() for background opacity alternation:
1 | const rgb = props.rgb; |
Random RGB numbers
The naive approach is just to generate random numbers for rgb:
1 | function random_rgb() { |
This gets me totally random numbers that could be very light or dark.
Using HSV
Hue, Saturation, and Value (HSV) is a color model that is often used in place of the RGB color model in graphics and paint programs. In using this color model, a color is specified then white or black is added to easily make color adjustments. HSV may also be called HSB (short for hue, saturation and brightness).
- S: 0(not colorful) -> 1(fully colourful)
- V: 0(black) -> 1(white)
So I want the saturation and value stable, but hue random.
1 | function generateRandomRGB() { |
Improve the distribution using golden ratio
This article recommended using golden ratio to achieve more evenly distributed hue.
The algorithm for this is extremely simple. Just add 1/Φ and modulo 1 for each subsequent color.
1 | function generateRandomRGB() { |
Reinforcing even distribution (not random)
Here’s another guy’s code using the new CSS functions hsl() and hsla() to colour an array of elements:
1 | var hue = 0; |
hsl() and hsla() take care of normalizing the hue to the [0, 360) range for you. 222.5 is approximately 360/Φ
Neat!