Paths
IE[a] | Firefox | Safari | Chrome | Opera | iPhone | Android |
|---|---|---|---|---|---|---|
7.0+ | 3.0+ | 3.0+ | 3.0+ | 10.0+ | 1.0+ | 1.0+ |
[a] Internet Explorer support requires the third-party explorercanvas library. | ||||||
Imagine you’re drawing a picture in ink. You don’t want to just dive in and start drawing, because you might make a mistake. Instead, you sketch the lines and curves with a pencil, and once you’re happy with it, you trace over your sketch in ink.
Each canvas has a path. Defining the path is like drawing with a pencil. You can draw whatever you like, but it won’t be part of the finished product until you pick up the quill and trace over your path in ink.
To draw straight lines in pencil, you use the following two methods:
moveTo(moves the pencil to the specified starting point.x,y)lineTo(draws a line to the specified ending point.x,y)
The more you call moveTo() and
lineTo(), the bigger the path gets.
These are “pencil” methods—you can call them as often as you like, but you
won’t see anything on the canvas until you call one of the “ink”
methods.
Let’s begin by drawing the off-white grid:
for (var x = 0.5; x < 500; x += 10) {
context.moveTo(x, 0);
context.lineTo(x, 375);
}for (var y = 0.5; y < 375; y += 10) {
context.moveTo(0, y);
context.lineTo(500, y);
}Those were all “pencil” methods. Nothing has actually been drawn on the canvas yet. We need an “ink” method to make it permanent:
context.strokeStyle = "#eee";
context.stroke();stroke() is one of the “ink”
methods. It takes the complex path you defined with all those moveTo() and ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access