An Introduction To HTML5 Canvas

JavaScript

01/05/2021


The HTML5 Canvas is a fantastic tool that allows us to show graphics of any kind. Yet, one should be aware that it merely serves as the container that houses these graphics. 👩‍🎨 The actual creation is done using JavaScript.

Setting the size

You can set the dimensions of the canvas using the height and width attributes. By default, a canvas has a width and height of 300px and 150px, respectively.

HTML
<canvas id="canvas" width="500" height="400" />

However, in most cases, you'll prefer to set the size dynamically. Let's make it as big as the page it's in.

JAVASCRIPT
document.addEventListener('load', () => {
const canvas = document.getElementById('canvas')
canvas.height = window.innerHeight
canvas.width = window.innerWidth
})

Retrieving the context

Let's keep things simple and create some shapes. 🔲 For that, we need to retrieve the 2D context.

JAVASCRIPT
const context = canvas.getContext("2d")

Imagine the context as an interface with properties and methods that allows us to perform the drawing. If we wanted to create a 3D graphic, we would instead have to pass in "webgl" as a value.

Drawing a square

To create rectangles and squares, the context offers the fillRect method. The first 2 parameters are the x and y coordinates (in that order) starting from the top-left corner. The 3rd and 4th are the width and height, respectively.

JAVASCRIPT
context.fillRect(0, 0, 100, 100) // Square fill

This function will fill in the body of the square. However, if you only want the outline, use strokeRect instead.

JAVASCRIPT
context.strokeRect(150, 0, 100, 100) // Square outline

Results of fillRect and strokeRect

Results of fillRect and strokeRect

For anything beyond a simple square, you will have to learn how paths work. 🙃

Paths explained

What's a path? I find MDN gives a pretty good explanation:

"A path is a list of points, connected by segments of lines that can be of different shapes, curved or not, of different width and of different color".

Creating a path

For this example, let's draw a triangle.

JAVASCRIPT
context.beginPath()
context.moveTo(100, 200) // x, y
context.lineTo(200, 200) // x, y
context.lineTo(200, 300) // x, y
context.stroke()

Result of code snippet

Execution order of points

Here's what happened: 👇

  • beginPath - tell the context that we want to create a path
  • moveTo - place our first point at the specified coordinates
  • lineTo - place the next point at the specified coordinates
  • stroke - draw the lines connecting the points

All that's left is to connect points 3 and 1, i.e. close the remaining path.

JAVASCRIPT
// [...]
context.closePath() // Add before stroke()
// [...]

Closing the triangle

Closing the triangle

Adding style

If everything were black, our lives would be quite dull, wouldn't it? 🥱 So let's give our triangle some style! We can set the thickness and color of our line using the properties lineWidth and strokeStyle.

JAVASCRIPT
context.lineWidth = 4
context.strokeStyle = '#2F7ED8' // Add before beginPath()
// [...]

It's important to remember that the styling has to be placed before the item(s) it should affect. In other words, if we were to place it after the final lineTo method, the above would not be applied.

To round it off, let's fill our triangle with another color.

JAVASCRIPT
// [...]
context.fillStyle = '#C0D8F3' // Add before fill()
context.fill() // Add before stroke()
// [...]

The function fill fills in the body of the shape with color. If the color's not specified, it defaults to black. Once again, order matters. ⚠️ If fillStyle were to come after fill, the styling would not be applied. Furthermore, these two lines of code are added before stroke so that the filling is not placed on top of the triangle outline, but underneath.

Styled triangle

Styled triangle

If you wish to play around with the code in this article, go ahead!


WRITTEN BY

Code and stuff