Drawing Paths

Most shapes on the canvas are built using paths. A path is a list of points connected by segments that can be different shapes (curved or straight) and different colors or widths.

To draw a path, follow these steps:

  1. Create the path using beginPath().
  2. Use drawing methods like moveTo() and lineTo() to add segments to the path.
  3. Optionally close the path using closePath().
  4. Once the path is complete, use stroke() or fill() to render it onto the canvas.

The 2D rendering context includes several methods for building paths:

Method Description
beginPath() Resets the current path. Always call this before starting a new shape.
moveTo(x, y) Moves the drawing position to the specified x and y coordinates without drawing a line.
lineTo(x, y) Adds a straight line segment from the current position to the specified x and y.
closePath() Attempts to close the current path by drawing a straight line back to the start. If the shape is already closed, it does nothing.
stroke() Renders the outline of the current path using the current strokeStyle.
fill() Renders a solid shape by filling the path's content area using the current fillStyle.

Triangle Example

This example draws a triangle using several path methods:

View Output

Paths can be much more than just straight lines. The next lesson will show how to add curves and circles to your paths.