Paths and lines
Learn to draw paths and lines with beginPath, moveTo, lineTo and stroke.
Drawing paths
To draw shapes other than rectangles you use a path. beginPath starts a new path. moveTo(x, y) lifts the pen to a point (moves without drawing), lineTo(x, y) draws a line to that point.
To put the line on the screen you call stroke. The path is a list of drawn segments; stroke makes that list visible.
closePath and stroke
closePath closes the path by connecting it back to the start, forming a closed shape. stroke draws the outline of the path, fill fills its inside. Without a closed path, fill does not work correctly.
For closed shapes like triangles, calling closePath automatically links the last corner to the first. You set colors with strokeStyle and fillStyle; both must be given before the drawing call.
Exercise Draw a triangle
Draw a triangle. Start the path with ctx.beginPath(), lift the pen to the first corner with ctx.moveTo(50, 10), draw two lines with ctx.lineTo(90, 80) and ctx.lineTo(10, 80), close the path with ctx.closePath() and stroke with ctx.stroke().
Show example solution
ctx.beginPath();
ctx.moveTo(50, 10);
ctx.lineTo(90, 80);
ctx.lineTo(10, 80);
ctx.closePath();
ctx.stroke();
Test yourself
-
Draw a line
ctx.beginPath(); ctx.moveTo(10, 10); ctx.____(100, 50); ctx.stroke();Show answer
ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(100, 50); ctx.stroke(); -
What does the beginPath method do?
- It immediately paints the drawing to the screen
- It deletes the previous path and clears the screen
- It sets the color
- It starts a new path
Show answer
It starts a new path — Correct! beginPath starts a new path; it clears previous path points.
-
Match the path methods
- beginPath
- start path
- moveTo
- lift pen
- lineTo
- draw line
- closePath
- close path