If you’re after a line or an open shape, rather than a closed polygon or circle, SVG has two options for you: lines and polylines.
Lines
The SVG line syntax may look slightly intimidating at first, but it’s simply being very precise: a line can only consist of two points, and each point is specified by two separate coordinates for x
and y
.
Unlike the shapes I’ve explored so far, lines are entirely invisible by default, and will remain so until at least a stroke
color is added; once colored, they will remain a hairline until stroke-width
specifies a thickness.
<svg width="300" height="300" viewBox="0 0 300 200" xmlns="http://www.w3.org/2000/svg">
<line x1="0" y1="0" x2="300" y2="200" stroke-width="20" stroke="black" />
</svg>
Polylines
Polylines are just continued, joined SVG lines with multiple points:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 414.3 231.4">
<polyline stroke="#000" stroke-width="6" fill="none" points="15.7,127.9 112.1,15 294.3,205 75,167.9 364.3,36.4 392.1,212.9 "/>
</svg>
Which produces:
Note that unlike a graphical drawing tool, placing the last point of a polyline at the same location as the opening point will not result in a “closed” shape. But you can still apply fill
to a shape:
I’ll have more to say about fill
in a future article; for now, it’s enough to note that while we can apply a fill
to a polyline, and it will usually work as expected, it will provide the appearance of a closed polygon, but it is not the same thing.
Caps & Corners
SVG lines that change direction don’t have to be rendered with hard corners; there are two other options, enabled through the stroke-linejoin
property: round
and bevel
, which do exactly what they imply. (Note that you may need to thicken the stroke in order to see any change). A third option, miter
, the sharp cornered kind, is the default.
Similarly, the ends of lines can be terminated with three different kinds of cap, using the stroke-linecap
property: round
(half circles), square
(lines are capped with a square, like aglets (the cap at the end of shoelaces), or butt
(the default)."
Being appearance properties, both stroke-linejoin
and stroke-linecap
can be applied as either attributes or CSS properties.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.