How the Z Command Closes SVG Path Shapes

The Z command (or z) in an SVG path d attribute is known as the “closepath” instruction. This article explains how the Z command mechanically functions by drawing a straight line from the current position back to the starting point of the active subpath, how it differs from manually drawing a line with the L command, and its critical impact on path rendering, stroke joins, and compound paths.

Mechanics of the Closepath Command

When an SVG rendering engine encounters the Z or z command in a path’s d attribute, it automatically draws a straight line from the current cursor position back to the coordinates of the most recent M (MoveTo) command.

Because the command takes no parameters, uppercase Z and lowercase z behave identically.

For example, consider the following triangle path:

<path d="M 10 10 L 50 10 L 30 50 Z" fill="orange" stroke="black" />
  1. M 10 10 establishes the start coordinate of the subpath at (10, 10).
  2. L 50 10 draws a line to (50, 10).
  3. L 30 50 draws a line to (30, 50).
  4. Z identifies (10, 10) as the subpath origin and connects (30, 50) directly back to (10, 10).

Stroke Joins vs. Line Caps

The most significant visual difference between closing a shape with Z versus drawing a final segment with L (LineTo) involves how borders are rendered.

Handling Multiple Subpaths

When an SVG <path> element contains multiple M commands, it creates multiple subpaths. The Z command only closes the subpath it is currently inside, targeting the initial point of the immediately preceding M command.

This functionality is essential for: - Creating shapes with cutouts or holes (such as a donut or the letter “O”) using the non-zero or even-odd fill rules. - Combining multiple independent closed shapes into a single performant SVG DOM node.

Once a Z command closes a subpath, the next coordinate command implicitly uses the closed subpath’s start point as its origin unless a new M command is issued.