Canvas

In this lesson, you will learn about HTML Canvas and how to use it for JavaScript game graphics.

We'll cover the following

The HTML canvas element provides a blank canvas on which we can draw our game. Drawing is a fundamental aspect of making our game, and we will focus on how we can draw on the canvas to make the graphics for our game.

Using canvas

The default size of the canvas is 300 pixels × 150 pixels (width × height). However, custom sizes can be defined using the HTML height and width properties. We add the canvas element to the HTML:

<canvas id="canvas"></canvas>

We can add a reference to the HTML <canvas> element in the DOM (Document Object Model) using the getElementById method.

let canvas = document.getElementById('canvas');

We have the canvas element available, but we cannot draw directly on it. We can use different rendering contexts.

Canvas context

The canvas has a 2D drawing context used for drawing shapes, text, images, and other objects. First, we choose the color and brush, and then we paint. We can change the brush and color before every new drawing, or we can continue with what we have.

The HTMLCanvasElement.getContext() method gets the canvas context, where we render the graphics. By supplying '2d'as the argument, we get the canvas 2D rendering context:

let ctx = canvas.getContext('2d');

Drawing

The last thing we need to do before drawing something is to choose a color.

ctx.fillStyle = 'red';

Once we have a canvas context, we can draw on it using the canvas context API. We can use fillRect() to draw a filled rectangle colored by the current fillStyle.

ctx.fillRect(x, y, width, height);

This draws a filled red rectangle. Since the pieces of our Tetris game are a bunch of rectangles, we already know enough to do the graphics for our game!

Animations

Canvas uses immediate rendering: When we draw, it immediately renders on the screen, but, it is a fire-and-forget system. After we paint something, the canvas forgets about the object and only knows it as pixels. So, there is no object that we can move. Instead, we have to draw it again.

Doing animations on Canvas is like making a stop-motion movie. In every frame, we need to move the objects a little bit to animate them.

We can use clearRect() to clean up the previous cell once we move onto the next. Using the width and height of the canvas, we can clean it between consecutive paints.

const {width, height} = this.ctx.canvas;
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, 10, 10);
ctx.clearRect(0, 0, width, height);
ctx.fillRect(1, 1, 10, 10);

Here is an example of the simplest of animations, including painting a blue square, cleaning the canvas, and then painting the blue square down and to the right a bit.

Now that we know the basics of canvas, it’s time to put this knowledge to use and start with the graphics of our game.

Get hands-on with 1200+ tech skills courses.