Abstract: How to programmatically randomize beautiful compatible color? This is a basic approach but can easily extended once the concept is grasped. The implementation is written in elixir but can be applied in any language.
In one of your project, you might encounter situation where you want to randomize color for background, variety of text, ect. One way to do it of course is just to provide it with an array of predefined options. Such as :
The example above randomize a list of hex color. Other than hex format, CSS understand RGB, and css color code. None of it can easily be manipulated programmatically other than using random function over predefined list.
Introducing HSV color system
There are other format called HSV (Hue, Saturation, Value). Here’s how it worked:
Hue (H) is represented as degree in color wheel, so it can have range from 1 to 359.
Saturation (S) is how ‘washed’ it is, with range from 1 to 100 (percentage).
Value (V) is how light or dark it is, with range from 1 to 100 (percentage).
Using this tool for example we can get the idea on how HSV can be easily converted into RGB or hex on the fly .
Reading the HSV to RGB spesification from wikipedia (https://en.wikipedia.org/wiki/HSL_and_HSV) we can make a function to convert HSV into RGB, and RGB to hex.
Now we can just call
hsv_to_hex(h,s,v) funtion to get the hex color.
Back to the question ` how we can randomly generate compatible color programmatically?`. The trick is just to set fixed Saturation and Value and randomize the Hue.
For example, set fixed Saturation to 50 and Value to 90 and randomize the H will produce something similar like this:
There we have it! A pretty color randomizer function. In the next article we can turn this function into an SVG Initial based avatar generator.