Path2D in Canvas
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)
The path methods we have written about in our previous posts are also present in the Path2D interface:
- Path2D.addPath()
- Path2D.closePath()
- Path2D.moveTo()
- Path2D.lineTo()
- Path2D.bezierCurveTo()
- Path2D.quadraticCurveTo()
- Path2D.arc
- Path2D.arcTo()
- Path2D.ellipse()
- Path2D.rect()
- Path2D.roundRect()
Take a look if you haven’t read them yet :)