We have discussed previuosly how to create paths and subpaths to create different shapes and figures. But the Canvas API offers us an interface as well for declaring a path that will be used a posteriori, that is to say, the Path2D interface. It then can be used in a CanvasRenderingContext2D object.

To create an object we need to call the Path2D constructor. Optionally we can add another path as an argument:

new Path2D()
new Path2D(path) // optional argument

Let’s see how we can create basic shapes with this interface:

const canvas = document.getElementById("canvas")
const context = canvas.getContext("2d")

/* 
Beginning a new path
and adding a rectangle
*/
const path1 = new Path2D()
path1.rect(5, 5, 60, 60)

/*
Beginning a second path
and adding an arc.
It also includes a copy of the path1 object.
*/
const path2 = new Path2D(path1)
path2.arc(120, 50, 50, 0, 2 * Math.PI);

/*
Rendering the path2 object which includes an arc
and a rectangle (as a result of the copy of path1).
*/
context.fill(path2)

path2d

The path methods we have written about in our previous posts are also present in the Path2D interface:

  1. Path2D.addPath()
  2. Path2D.closePath()
  3. Path2D.moveTo()
  4. Path2D.lineTo()
  5. Path2D.bezierCurveTo()
  6. Path2D.quadraticCurveTo()
  7. Path2D.arc
  8. Path2D.arcTo()
  9. Path2D.ellipse()
  10. Path2D.rect()
  11. Path2D.roundRect()

Take a look if you haven’t read them yet :)