Introduction to the Canvas!

Marshall Slemp
4 min readNov 9, 2020

We are going to introduce the Canvas API for HTML5 and build a quick project that allows a square to bounce off the walls of the canvas. I am going to assume you already know a some HTML and JavaScript, it’s going to be a simple tutorial so don’t worry too much if your brand new!

Let’s get started!

First, let’s make sure we have a html file and we can add our Canvas element to it! We will also create a main.js file and link it to our HTML as well. Our HTML file should look something like this:

HTML file with canvas and js script

Here we have a HTML file with just a Canvas element inside the body. If you open this file in the browser, you will see a blank page but the Canvas is there! Let’s open our JS file so we can start interacting with the Canvas.

Add the following code to your main.js file and refresh the browser!

const canvas = document.getElementById("canvas");canvas.style.backgroundColor = "lightgray";const ctx = canvas.getContext('2d')ctx.fillRect(0, 0, 50, 50);

You should see a square inside our canvas! Not great but you can mess with the background color if you want. You can also change the square by changing the fillStyle:

const canvas = document.getElementById("canvas")canvas.style.backgroundColor = "lightgray";const ctx = canvas.getContext('2d')ctx.fillStyle = "blue"; //ADD COLOR OF CHOICE HERE!ctx.fillRect(0, 0, 50, 50)

Let’s breakdown the code above:

  1. We grab the canvas by the ID and store a reference to it in the variable canvas.
  2. We can add styles to elements using JavaScript accessing the style object on the element. Note: This is not the way to style or add color to shapes drawn on the Canvas , only the canvas element itself! You could also use CSS to style the canvas element.
  3. We call canvas.getContext(‘2d’) which returns the drawing context on the canvas and store it in the variable ctx. There are other drawing contexts like webgl but we will focus on 2d (two dimensional) context!
  4. ctx.fillStyle is used to set the color of the shape that we are about to draw on the canvas.
  5. ctx.fillRect is used to draw a rectangle. It takes 4 argument — x,y,width,height. The x and y coordinates start at the top left of the canvas.

Also, when we draw to the canvas it stays there until we clear it. For example if we add a couple more fillRects to our code we dont erase the previous rectangle, we just add more. Add a few more rectangles and refresh the browser.

const canvas = document.getElementById("canvas")canvas.style.backgroundColor = "lightgray";const ctx = canvas.getContext('2d')ctx.fillStyle = "blue"ctx.fillRect(0, 0, 50, 50)ctx.fillRect(50, 50, 50, 50)ctx.fillRect(100, 100, 50, 50)ctx.fillRect(150, 150, 50, 50)

We can clear the entire canvas by canvas.clearRect(0,0,canvas.width,canvas.height).

Let’s make the square move across the canvas. Make you js file look like this and refresh the browser.

const canvas = document.getElementById("canvas")canvas.style.backgroundColor = "lightgray";const ctx = canvas.getContext('2d')let x = 0let y = 0ctx.fillStyle = "blue"function drawSquare() {   ctx.clearRect(0, 0, canvas.width, canvas.height)   x += 1   ctx.fillRect(x, y, 50, 50)   requestAnimationFrame(drawSquare)}drawSquare()

You should see the blue rectangle(square) move across the canvas and disappear. We can also increment the y variable and watch the square move right and down.

Let’s check to see if the square hits the side and reverse it’s direction.

const canvas = document.getElementById("canvas")canvas.style.backgroundColor = "lightgray";const ctx = canvas.getContext('2d')let x = 0let y = 0let dx = 1 let dy = 1ctx.fillStyle = "blue"function drawSquare() {  ctx.clearRect(0, 0, canvas.width, canvas.height)  if (x + 50 >= canvas.width || x < 0) {    dx = -dx  }  if (y + 50 >= canvas.height || y < 0) {    dy = -dy  }  x += dx  y += dy  ctx.fillRect(x, y, 50, 50)  requestAnimationFrame(drawSquare)}drawSquare()

Now we will change direction when we hit an edge. The if statements check to see if the square at the current x or y position plus its width or height is equal to the canvas width or canvas height — if it is, invert dx or dy. Change the dx or dy variables to see the square take a less predictive route and speed up or slow down the square.Basic Collision Detection.

This is an intro into using the Canvas API. You can go on to build a game using HTML5 Canvas. Keeping playing around with the canvas, change variables, make multiple square and have fun!

--

--