(click anywhere to close)

[Canvas] Paths

category: Website | course: Canvas | difficulty:
1. Displaying Paths

Essentially, every shape you draw is a bunch of points connected with lines, which we call a path. A path has to start somewhere, and can be closed when we’ve created all the necessary parts. For example, a rectangle is a path of four points with straight lines connecting them.

To create a path, use

beginPath(); any path methods closePath();

Closing the path is not strictly necessary, as beginning a new path automatically tells JavaScript that the previous one should be closed (we can’t nest paths inside paths). The closePath() method therefore connects the first and last point with a straight line, literally closing the path.

Displaying Paths

Creating a path, however, is not enough to display it. Now JavaScript has a bunch of points connected in certain ways, but it doesn’t know, for example, what colour to use. There are two different components of a path that can be styled, which is the stroke and the fill.

The stroke is the actual path, or outline of the path. When you draw a straight line between two points, you can display the line by displaying the stroke of the path.

To stroke the last shape you created, use stroke()

The fill is how a path is filled. When you draw a rectangle, you can make it a blue rectangle by changing the fill to be blue.

To fill the last shape you created, use fill()

//At this point, nothing is displayed yet
//Now the rectangle is filled and outlined with black
//Because the rectangle already is a closed shape, closePath() is not needed

As you might have noticed, we still haven’t said anything about the colours or techniques to use for stroking/filling, in which case the canvas defaults to black. Throughout this course you’ll learn ways to do that, but for now I want to focus on those path methods that actually create the shapes you want.

Do you like my tutorials?
To keep this site running, donate some motivational food!
Chocolate Milk