Many developers use random color generation to provide a awesome looking UI to their websites. For generating random color codes using JavaScript you need to learn basics of color theory and maths. In this post I will be explaining color theory, basic math functions and random color generating methods.
Introduction to RGB color theory
Every color pixel is made up of three major color’s: red, green and blue. Different intensity(amount) of these three color’s per pixel produce different range of color’s per pixel. Red, green and blue are called primary colors.
The total number of colors supported by a computer(or monitor) depends on the number of bytes allocated to each of primary colors.
8 bit color system
In 8 bit color systems each primary color can have a intensity range of 0 to 255. Therefore producing 256*256*256 i.e., 16777216 different colors.
16 bit color systems
Similarly we can calculate for 16 bit color monitors. The total number of colors supported are 65536*65536*65536.
Similarly we can calculate for 32 bit and 64 bit color systems.
More on RGB model
RGB for web design
Web browsers support only 8bit colors. Although the monitor is of higher bits, the browser is limited to supporting 8bit colors only. More on Web Colors.
Math.random and Math.floor
Math.random is a JavaScript function that returns a random number from 0 to 1(not including 1).
Math.floor function returns the largest integer less than or equal to a number.
Generating random color
This is a simple example to generate random colors in javascript.
Generating random colors using randomColor JavaScript Library
David Merfield has created a awesome JavaScript library to generate random colors. Its called as randomColor. Its provide features for similar colors, attractive colors, selective colors and much more functionality. It can be used for data visualization and arts.