The Path2D object
Summary: The Path2D object can be used to create and maintain multiple paths for the canvas tag. It acts as a cache for paths so that you can replay and/or test them as required.
The Path2D object is new to canvas as of March 2014 and can be used to
cache drawing commands and replay them or test
them for hits as required. It was formally called the Path object and
was added to the specification in early 2012. You can
either create new Path2D objects and then use the API to specify the
path (eg path.moveTo()
, path.lineTo()
etc)
or you can
use SVG path syntax as an argument to the constructor. You can also
give the constructor another Path2D object and the
resultant object will be a combination of the two.
The beginPath()
function can be used to "reset" the canvas
path - throwing away whatever the current path is. It
does not however throw away any Path2D objects that you have created and
nor does creating a Path2D object "reset" the
canvas tags default path. So in this way Path2D objects can be seen as a
little separated from the canvas.
Arguments to the objects constructor
-
The basic way to create a Path2D object with no arguments given to the constructor. This creates an empty Path2D object which you then use for drawing with.
// Creates an empty path path = new Path2D();
-
If you want to use an SVG path to specify drawing commands you can pass the string to the constructor. In this way you can pass path information around - including transmitting it over a network and/or serializing them for storage (eg in a file or database).
// Creates a path based on the SVG path given path = new Path2D('M 100,100 h 50 v 50 h 50');
-
If you already have a path object that you want to start with - eg a base path that you "inherit" from - you can give it to the constructor and the new path object will be initialised with that path data.
<script> window.onload = function () { var canvas = document.getElementById("cvs"); var context = canvas.getContext('2d'); // Create a rectangle but do not stroke or fill it var path1 = new Path2D(); path1.rect(5,5,90,90); // Creates a new path initialised with the existing path1 var path2 = new Path2D(path1); path2.rect(205,205,90,90); // After stroking BOTH rectangles will be painted to the canvas context.stroke(path2); } </script>