HTML & CSS
Article
By Craig Buckler

How to Create Complex Paths in SVGs

By Craig Buckler
Last chance to win! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

In this series we’ve discovered what SVGs are, why you should consider them and how you can embed them in your web pages. We’ve also discussed basic drawing elements but you’ll soon move beyond simple lines, rectangles and ellipses.

SVG paths are a far more advanced. It could be argued that 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" />

What does that mean? It looks like meaningless garbage but there is logic behind it.

The path element requires a single ‘d’ attribute which is a string containing a list of encoded drawing instructions. It’s not quite as complex as regular expression syntax but it’s still easy to become confused.

The drawing string is formed using a series of commands identified by an upper or lowercase letter. This is followed by zero or more arguments which apply to that command. For example, the following path moves the pen to a starting point at 500,500 without drawing a line:


<path d="M500,500" />

Similarly, a lowercase ‘m’ moves the pen relative to its current location, e.g. 50 units left and 100 units up (remember that SVG viewboxes normally start at 0,0 in the top-left corner):


<path d="m50,-100" />

Drawing lines is similar; ‘L’ draws a line to absolute co-ordinates and ‘l’ draws a line relative to the current location. The following paths are 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, e.g.


<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’ closes 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 subpaths, e.g.


<path d="M500,500 L500,200 L800,500 z M400,600 L400,900 L100,600 z" />

produces:

SVG paths

Now you have a path, the element can be styled with CSS or you can add stroke, stroke-width, fill and other attributes as required.

If you’re thinking this is easy, it’s possibly best to rest now and prepare yourself. In my next SVG article we’ll discuss cubic Bézier curves, quadratic Bézier curves and elliptical arcs…

Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.
Is it good?Is it good?