Creating a Colorful Grid with Canvas HTML and JavaScript

·

3 min read

Creating a Colorful Grid with Canvas HTML and JavaScript

In this article, we will explore a snippet of code that uses Canvas HTML and JavaScript to create a beautiful and colorful grid. Let's dive in and understand how this code works.

First we need a HTML to show colorful grid, I used tailwindcss for this.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Color Grid</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body> 
    <script src="color.js"></script>
</body>
</html>

inside color.js we will have some variables to start make canvas tag.

//create a <canvas> tag
const createCanvas = document.createElement("canvas");
//assign for canvas tag an id "canvas"
createCanvas.id = "canvas";
//show <canvas> inside html
document.body.appendChild(createCanvas);
/*
initialize fullWidth is 100% width and fullHeight is 100% height
they make our canvas show in full window
*/
const fullWidth = window.innerWidth;
const fullHeight = window.innerHeight;
//initialize canvas use getElementById method
const canvas = document.getElementById("canvas");
//assign width and height
canvas.width = fullWidth;
canvas.height = fullHeight;

Now, let's dive into using the Canvas API to draw on the screen. In this article, we will focus on working with the 2D context type. We will explore other context types in future posts.

/*
    The HTMLCanvasElement.getContext() method 
    returns a drawing context on the canvas, 
    or null if the context identifier is not supported, 
    or the canvas has already been set to a different context mode.
*/
/*
    2d - contextType: A string containing
    the context identifier defining the drawing context
    associated to the canvas.
    https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext#contexttype
*/
const context = canvas.getContext('2d')

Next, we define variables for the number of columns (cols) and rows (rows). We also initialize an empty 2D array called c to store the random RGB color values for each grid cell. The sizeX and sizeY variables represent the width and height of each grid cell.

let 
    //2D array is empty
    c = [],
    //initialize size of rectage 
    sizeX = fullWidth / 10,
    sizeY = fullHeight / 10,
    //initialize how many cols and rows
    cols = fullWidth / sizeX,
    rows = fullHeight / sizeY;

We then use nested loops to populate the c array with random RGB color values for each grid cell.

for (let i = 0; i < cols; i++) {
    c[i] = []
    for (let j = 0; j < rows; j++) {
        c[i][j] = `rgb(
            ${Math.floor(256 * Math.random())},
            ${Math.floor(256 * Math.random())},
            ${Math.floor(256 * Math.random())})`
    }
}

Moving on, we use another set of nested loops to iterate through each grid cell and draw a rectangle on the canvas. We set the fill style of the canvas context (context.fillStyle) to the corresponding color from the c array. Then, we use the fillRect method to draw a rectangle at the appropriate position and size, based on the current i and j values.

for (let i = 0; i < cols; i++) {
  for (let j = 0; j < rows; j++) {
    context.fillStyle= c[i][j];
    context.fillRect(i * sizeX, j * sizeY, sizeX, sizeY);
  }
}

By running this code, you will be able to generate a vibrant and dynamic grid with random colors. Feel free to customize the code and experiment with different variations to create your own artistic compositions using Canvas HTML and JavaScript. This article will be where we start working with creative coding.

Happy coding.