In this series of SVG articles, you’ve discovered what SVGs are, why you should consider them and how you can embed them in your web pages. You’ve also seen basic drawing elements, but most images move beyond simple lines, rectangles, and ellipses.
The SVG path element is far more advanced. It could be argued it’s the only element you ever need because it can draw any shape you desire. However, there’s one drawback, which is best illustrated with an example:
<path d="M500,500 L500,20 A480,480 0 0,1 968,607 z" />
It looks complicated and can be difficult to follow.
The path element requires a single d
attribute with a string value containing a list of encoded drawing instructions. It’s not as complex as a regular expression, but it’s easy to become lost in the number jungle.
The drawing string is formed using a series of commands identified by an upper- or lowercase letter. The letter is followed by zero or more arguments which apply to that specific command. For example, the following path uses an M
command to move the SVG pen to a starting point at 500,500 without drawing a line:
<path d="M500,500" />
The SVG viewBox
attribute affects the pen’s location within the image itself. Using the 500,500
example above, the pen would be:
- centered horizontally and vertically when the SVG uses
viewBox="0 0 1000 1000"
- positioned at the top left when
viewBox="500 500 1000 1000"
- positioned at the bottom right when
viewBox="-500 -500 1000 1000"
- outside the visible area when
viewBox="0 0 400 400"
.
Similarly, a lowercase m
moves the pen relative to its current location — for example, 50
units left and 100
units up:
<path d="m50,-100" />
Drawing lines is similar: L
draws a line to absolute co-ordinates, and l
(lowercase L
) draws a line relative to the current location. The following paths are therefore identical:
<path d="M500,500 L100,600" /> <path d="M500,500 l-400,100" />
H
and h
draw horizontal lines to an absolute or relative x
location accordingly. For example:
<path d="M500,500 H800" /> <path d="M500,500 h300" />
Bonus points if you can guess what V
and v
do …
<path d="M500,500 V400" /> <path d="M500,500 v-100" />
Finally, Z
or z
close the path by drawing a line from the current point to the starting point. Normally, Z
would be the last command in your string, although it’s possible to create strings with multiple sub-paths. For example:
<path d="M500,500 L500,200 L800,500 z M400,600 L400,900 L100,600 z" />
Continue reading How to Create Complex Paths in SVGs on SitePoint.