One Shape to Rule Them All

Well... A path really. If you have ever used something like the Pen tool in Affinity Designer or Adobe Illustrator, you know how unbeatable it is when it comes to drawing complex shapes. Paths brings exactly that to SVG.

While <path> theoretically is all you will ever need, the semantics and ease-of-use of the basic shapes, covered in my previous  article, sometimes trump its initial ambiguity. Rectangles and ellipses come to mind, but, in many cases, it won’t.

To me, as good a starting point as any in getting familiar with <path>, is recreating the other shapes.

Line Commands

<path> has a d attribute that works much in the same way points does for <poly*> shapes. Basically a list of points in a coordinate system, but the key difference is that paths also come with a bunch of different commands, separated into two group: lines and curves.

Turns out, drawing a simple line like above can be done in quite a few ways actually. Let’s see how a diagonal line running from the bottom left to top right could be drawn using the line commands L and l.

<svg viewBox="0 0 200 100" width="200" height="100">
  <path d="M 10,90 L 90,10"></path>
  <path d="M 110,90 l 80,-80"></path>
</svg>

Barely a stone throw away from how <polyline> and <polygon> shapes are defined.

Several Lines Make a Rectangle

Coming from just having drawn some lines above to creating a rectangle is not a huge leap. While it does introduce some new commands, they work a lot like L and l. What’s new here though is z, which is the command to complete or close out the shape — exactly how a <polygon> behaves — by automatically drawing a line to the starting point.

<svg viewBox="0 0 300 100" width="300" height="100">
  <path d="M 10,10 L 10,90 90,90 90,10 z"></path>
  <path d="M 110,10 H 190 V 90 H 110 z"></path>
  <path d="M 210,10 h 80 v 80 h -80 z"></path>
</svg>

Breaking it down into more normal language, it would read something like this.

M 10,10 L 10,90 90,90 90,10 z

Move to 10,10 and draw a Line to the point 10,90 followed by 90,90 and 90,10 before finally completing the shape.

M 110,10 H 190 V 90 H 110 z

Move to 110,10 and draw horizontally to where x is equal to 190, vertically to there y is 90 and horizontally again to where x is 110. Complete the shape.

M 210,10 h 80 v 80 h -80 z

Move to 210,10 and draw a line horizontally 80 units, vertically 80 units and then horizontally again -80 units. Finish by completing the shape.

You’re starting to see the picture.

The Impossible Triangle

My buddy  has this super cool lithography of a penrose triangle , perhaps more commonly known as the impossible triangle, hanging in his apartment; it’s the perfect thing to try and recreate.

Et voilà. While the limitations imposed by only drawing straight lines should not be underestimated when it comes to creativity, <path> can do so much more. But it’s best to let things marinate.

Happy coding!