We will build a project called Change The Background Color to illustrate these concepts. You can see the demo here.
In this tutorial, we will:
- learn how computers understand the concept of colors
- learn about the hexadecimal system and its usefulness to computers
- learn how to separate concerns in your code
- use this new knowledge to generate colors in hexadecimal
- click a button in our HTML code to call our functions
- change the body style background-color when the button is clicked
This article should be accessible to anyone who is familiar with variables and how to create them in any programming language.
What We'll Cover
- How Computers Understand Colors
- What is the Hexadecimal System?
- How Hexadecimal Is Used In Color Spaces
- How to Generate Colors With Hexadecimals
How Computers Understand Colors
Computer displays use tiny dots called pixels to display colors by mixing red, green, and blue light.
To interpret and manipulate colors, computers use mathematical models called color spaces. By converting colors into a specific color space, computers can modify and adjust them before displaying them on the screen.
There are many different types of color spaces, each with its own way of representing colors. Here are some examples:
- RGB (Red, Green, Blue): This is the most common color space used in computer graphics, and it represents colors by mixing different amounts of red, green, and blue components.
- CMYK (Cyan, Magenta, Yellow, Black): This is a color space used in printing, where colors are created by overlaying dots of different colors on top of each other.
- HSL (Hue, Saturation, Lightness): This color space represents colors based on their hue (which color they are), saturation (how intense the color is), and lightness (how bright or dark the color is).
- LAB (Lightness, A, B): This color space is used in digital imaging and represents colors based on their lightness, as well as their position on two color axes: A (from green to red) and B (from blue to yellow).
- XYZ: This color space represents colors based on the amount of light that they reflect or emit, and is often used in color matching applications.
What is the Hexadecimal System?
Hexadecimal (or simply "hex") is a base-16 numbering system that is commonly used in computing and digital electronics.
In this system, numbers are represented using 16 digits: the regular decimal digits 0 through 9, plus the letters A through F which represent values 10 through 15.
Hexadecimal is often used in computing because it provides a compact and easy-to-read way to represent binary numbers. Each hex digit corresponds to four binary digits, or bits, which means that two hexadecimal digits can represent a byte of data (8 bits).
How Hexadecimal Is Used In Color Spaces
Hexadecimal is commonly used to represent colors in various color spaces, particularly in digital media.
Each component in RGB can have a value between 0 and 255, and these values can be converted to hexadecimal notation using a base-16 numbering system.
In RGB hexadecimal notation, each component is represented by a two-digit hexadecimal number, which can range from 00 to FF.
How to Generate Colors With Hexadecimals
Our goal in this section is to build the demo project. The demo project is a button. On clicking this button, a color is generated that changes the background of the HTML webpage.
There are the 6 steps to building the project. We'll walk through them one by one.
1. Represent hexadecimals using an array
const hexCharacters = [0,1,2,3,4,5,6,7,8,9,"A","B","C","D","E","F"]
2. Create a function to extract items from this array
getCharacter will take the index and return the hexademical-character stored in that place. This helps us as we pick our colors.
3. Represent colors using the extracted value
A hexadecimal representation of RGB starts with
# followed by 6 characters selected from our array. Thus, the function
getCharacters will be called 6 times. We can employ a for-loop to call our function faster.
generateJustOneColor() generates a random hexadecimal color code represented as a string.
The function starts by declaring a variable named hexColorRep and initializing it with the # character.
Next, the function uses a for loop to generate the next six characters of the color code. The loop runs six times because each color code is represented by six hexadecimal digits.
Within the loop, the function calls another function named
getCharacter() to generate a hexadecimal digit for each position of the color code. The
position parameter is passed to the
getCharacter() function to indicate which digit is being generated.
Once all six digits of the color code have been generated, the function returns the full color code as a string.
The above code will to return this same result/color given the same
position for our for-loop. So we need to introduce randomness. This means our selection of the characters must have the element of surprise.
4. Improve our code to generate random colors
Math.random() is one of the ways to introduce randomness.
Math.random() gives a new result every time it is called in range
0 to 1.
Math.random() function generates a random decimal number between 0 (inclusive) and 1 (exclusive), we can manipulate this value to obtain a random integer between 0 and 15.
This is done by multiplying the random decimal number by the desired range of integers (in this case, 16) and then applying the
Math.floor() method to round down the result to the nearest integer. This will ensure that the output is within the desired range of integers.
For example, if
Math.random() generates the value
0.435, multiplying it by 16 would result in
Math.floor() to this result would then round it down to
6, which is a random integer within the range of 0 to 15.
Math.floor() performs 2 roles here: it helps us avoid a RangeError by rounding-down the extremes (the maximum number will be 15) and ensures we always return an integer.
We have all the ingredients needed to generate our colour, so now we can combine them together. Each hex-colour must start with a "#" and be followed by 6 characters.
generateNewColor() function is the main function of the program that generates the random hexadecimal color code. It starts by initializing a string variable named "hexColorRep" with the "#" character, as all hexadecimal color codes begin with this character.
Next, the function uses a for loop to generate six random characters for the color code. Within the loop, the function generates a random position within the range of the "hexCharacters" array using the
Math.random() function and the length of the
hexCharacters array. This random position is then used to obtain a random character from the
hexCharacters array using the
getCharacter() function. The resulting character is appended to the
hexColorRep string variable.
generateNewColor() function returns the complete hexadecimal color code represented as a string.
5. Create an interface to present our code
We need an interface so users can interact with our code and see the magic we have created.
6. Connect the button to the function using an event
Our goal is to change the background-color style of this HTML page.
This program that sets the background color of a webpage to a randomly generated hexadecimal color code when a button is clicked.
The program begins by defining two variables using the
document.getElementById() method. The
btn variable represents the button element on the webpage with the ID
b, while the
bgColor variable represents a text element on the webpage with the ID
Next, the program attaches an event listener to the
btn element using the
addEventListener() method. This listener listens for the
click event on the button. When triggered, it executes a function that generates a new random color code using the
The resulting color code is then assigned to the background color of the webpage using the
style.backgroundColor property of the
document.body element. This causes the entire webpage to be updated with the new color.
Finally, the color code is also displayed in the
bgColor element on the webpage using the textContent property.
You can see the full code here.
In the demo project, the generated colour was passed as background to an HTML page. This is why on clicking the button, a new colour gets generated, and updates the background-color style of the page. Check out the full code here.
If you want to see more of teachings, check out Xutini - the fun way to learn digital skills.