5) Canvas Lesson

Draw a Triangle on a Canvas with JavaScript

4 min to complete · By Ian Currie

In this lesson, you will draw triangles using the CanvasRenderingContext2D API.

Learn by Doing

You may note from your brief incursions into the Canvas API, that in all the 2D rendering context methods, there are no methods for triangles. So, now you will implement your own function to draw a triangle.

Try using what you've learned so far to code a function that will draw a triangle.

If you're doing this course step-by-step, and especially if you're in the mentorship program, please be sure to push your work to GitHub when you're done.


Understand Triangle Basics

What are triangles at their most fundamental? How many sides does a triangle have? What method already covered might you use to draw one? What is the minimum amount of information you need for this?

3 points. That is, 3 x and y positions to join together with lines.

So the function signature will look something like this:

// basics.js

// ...

function drawTriangle(x1, y1, x2, y2, x3, y3) {
	// ...
}

That is quite a few arguments, but that is all information that is vital for drawing a triangle. Filling out the function body, you might have something like this:

// basics.js

// ...

function drawTriangle(x1, y1, x2, y2, x3, y3) {
	ctx.beginPath();
	ctx.moveTo(x1, y1);
	ctx.lineTo(x2, y2);
	ctx.lineTo(x3, y3);
	ctx.lineTo(x1, y1);
	ctx.stroke();
}

This function:

  • Assumes that there is a ctx variable in the enclosing scope
  • Starts a new path
  • Moves the cursor to the first point
  • Uses .lineTo() three times to go to all the points
  • Finally uses .stroke() to draw the triangle

The assumption that the function makes about the ctx variable makes it an "impure" function. The immediate way you could make this function pure is by passing in the ctx variable to the function. Though, that can get a bit tedious.

Later, with classes, you'll see other ways to organize this into a more logical and self-contained package, effectively designing your own drawing API around the canvas API.

Summary: How to Draw a Canvas Triangle

  • You will need 3 positions since a triangle has 3 sides
  • Create a function that:
    • Starts a new path with the beginPath() method
    • Moves the cursor to the first point with the moveTo() method
    • Uses the lineTo() method to go to all three points
    • Draws the triangle with the stroke() method