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" />M 10 10establishes the start coordinate of the subpath at(10, 10).L 50 10draws a line to(50, 10).L 30 50draws a line to(30, 50).Zidentifies(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.
- Manual Line (
Lto start): The path remains technically “open.” The rendering engine appliesstroke-linecap(butt, round, or square) to the start and end points, which can leave a visible gap, overlap, or misaligned corner at the junction. - Closepath (
Z): The path is marked as closed. The rendering engine treats the initial vertex as a corner rather than two overlapping endpoints, seamlessly applying the definedstroke-linejoin(miter, round, or bevel).
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.