HTML5 Canvas API Tutorial Part 3 - Lines and Polygons

Published: Monday, January 11, 2021
Updated: Monday, February 1, 2021

Greetings, friends! This is Part 3 of my HTML5 Canvas API tutorial. If you're new to this series, please read Part 1.

Drawing Lines

Today, I will discuss how to draw lines with the HTML5 Canvas API. This is an important fundamental skill to learn because it helps you draw any kind of shape you want, including triangles, stars, and even more complex shapes.

Before we begin, make sure you have a file named index.html with the following contents:

html
Copied! ⭐️
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas API Tutorial</title>
</head>
<body>
  <h1>Canvas API Tutorial</h1>
  <canvas id="canvas" width="500" height="500" style="border: 1px solid black;"></canvas>
  <script src="canvas.js"></script>
</body>
</html>

This will setup a new canvas with a width and height of 500 pixels and add a visible border around it. Drawing lines is very simple with the Canvas API, but you need to make sure you understand the 2D canvas coordinate system.

Remember, the origin is located on the top-left corner of the canvas. This is different from typical coordinate systems you may have learned in algebra classes in high school. The x-axis increases as you go right, and the y-axis increases as you go down.

Coordinate system for 2D HTML5 Canvas

To draw a line on our canvas, place the following code in your canvas.js file:

js
Copied! ⭐️
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

ctx.strokeStyle = 'blue' // Set line color to blue
ctx.beginPath() // Start a new path
ctx.moveTo(0, 0) // Move the pen to (0, 0)
ctx.lineTo(200, 200) // Draw a line to (200, 200)
ctx.stroke() // End path

You should see a blue diagonal line going from the point, (0, 0) on the canvas to the point, (200, 200).

Blue diagonal line drawn to the HTML5 canvas

Let's examine what's happening in the above code. We first set the stroke color to blue. When we draw lines on the canvas, we are dealing with only strokes, not shapes that have any sort of fill color.

Next, we begin a new path and move to the point, (0, 0) on our canvas. Imagine you have a sheet of paper in front of you, and you're drawing with a pencil. You will place your pencil first down on (0, 0) and then draw a line to the point, (200, 200). To render the line to the canvas, you must close your path. Since we're dealing with lines, we'll use the ctx.stroke method to close the path.

Hopefully, the illustration below helps demonstrate how the coordinate system works in regards to drawing lines on the canvas.

Coordinate system for 2D HTML5 Canvas with our blue diagonal line

Drawing Triangles

We can use our knowledge of drawing lines to draw polygons such as triangles. You're probably wondering why there isn't a "triangle" method. Why do we have to draw lines to form a triangle? The HTML5 Canvas API is very low-level. That is, it's meant to be a bare-bones API that can be used to draw primitive objects such as lines, arcs, circles, and rectangles.

There are many libraries created by the community that utilize the HTML5 Canvas API to create tons of different shapes for you in a declarative manner. These libraries provide a "high-level" API because they build from the fundamental methods available in the Canvas API and provide tools for building more complex shapes or applications.

tip
You will see the terms "low-level" and "high-level" a lot throughout your programming career. Software developers like to create different levels of abstraction to help mask the complexities of "low-level" code and/or provide a different interface for building applications.

If, at this moment, you realize you want to use a library that already lets you build lots of shapes for you, then I recommend the p5.js library. However, I encourage you to continue reading, so you can build great libraries just like this one! 😃

If you want to draw polygons other than rectangles, then you may need to utilize some geometry knowledge. For something as simple as a triangle, we just need to know how to connect three lines together 😅.

The idea is to move to a start position on our canvas and then keep drawing lines until we have formed a triangle. As we draw lines, we are moving to the coordinate the line ends at. We will eventually end back at the starting point of (200, 200).

Coordinate system for 2D HTML5 Canvas with a blue triangle

Inside the canvas.js file, replace all the code with the following:

js
Copied! ⭐️
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

ctx.fillStyle = 'blue'
ctx.beginPath()
ctx.moveTo(200, 200)
ctx.lineTo(300, 200)
ctx.lineTo(300, 100)
ctx.lineTo(200, 200)
ctx.fill()

You should end up with a canvas that looks like this:

Blue triangle drawn to the HTML5 canvas

Notice that we now use ctx.fill to close the path because we want to fill in the triangle with a solid color. We also changed the fillStyle property to blue before drawing our triangle to the canvas.

Conclusion

Lines in the HTML5 Canvas API are fundamental building blocks for drawing all kinds of shapes. Once you know all the fundamentals, you'll be on your way to creating amazing applications!