SVG Polygon vs Polyline: Key Differences Explained
Scalable Vector Graphics (SVG) uses both the
<polygon> and <polyline> elements
to draw multi-segmented shapes defined by a series of connected
coordinate points. While both elements share a nearly identical syntax
centered around the points attribute, their fundamental
difference lies in how they handle the final path segment:
<polygon> automatically closes the shape by drawing a
line from the last point back to the first, whereas
<polyline> creates an open-ended series of connected
lines.
The Core Difference: Path Closure
The primary distinction between <polygon> and
<polyline> is the automatic closure of the path.
<polygon>: Designed specifically for closed geometric shapes. The rendering engine always creates an implicit closing segment connecting the final coordinate directly to the starting coordinate.<polyline>: Designed for open connected paths. The line terminates at the final specified coordinate and does not connect back to the starting coordinate unless you explicitly repeat the first point at the end of your points list.
Syntax Comparison
Both elements use the points attribute to define a list
of x,y coordinates.
SVG Polygon Example
<svg width="120" height="120">
<polygon points="20,20 100,20 100,100" fill="none" stroke="black" stroke-width="2" />
</svg>In this example, three points are defined. The browser renders a
complete triangle because the <polygon> element
automatically adds the third side between (100,100) and
(20,20).
SVG Polyline Example
<svg width="120" height="120">
<polyline points="20,20 100,20 100,100" fill="none" stroke="black" stroke-width="2" />
</svg>Using the exact same coordinates, the <polyline>
element renders only two connected line segments (an “L” shape). The
path remains open between the final coordinate and the start
coordinate.
Rendering Behavior: Stroke vs. Fill
Understanding how SVG fills and strokes interact with these elements is crucial for achieving the intended visual result:
- Stroke Rendering: The stroke of a
<polygon>covers the entire perimeter, including the closure segment. On a<polyline>, the stroke is applied only to the explicitly defined line segments, leaving the gap un-stroked. - Fill Rendering: By default, SVG elements have a
black fill (
fill="black"). If you apply a fill color to a<polyline>, the rendering engine will fill the interior space between the points as if it were closed, even though the stroke remains open. To avoid visual glitches, unclosed polylines often requirefill="none".
When to Use Each Element
- Use
<polygon>when creating fully enclosed geometric figures, such as triangles, pentagons, stars, hexagons, or any custom closed vector shape. - Use
<polyline>for continuous open lines, such as line charts, trend lines, zig-zags, electrical schematics, or multi-step route maps.