26: Forcing Shapes to be Paths

Avatar of Chris Coyier
Chris Coyier on

This is a little esoteric of a thing, I just needed to do it myself one time and found it confusing so I thought I’d do a whole video on it.

The thing is, not everything is a <path> in SVG. <path> is fantastic because it can be anything. But the syntax for it is just a bit more complex than any of the other shapes. So (maybe for that reason?) Illustrator always outputs the shapes in SVG with the most closely appropriate element. Rectangles are <rect>, other shapes made up of only straight lines are a <polygon>, or if it’s an open shape a <polyline>, etc.

That would be fine, except the DOM methods for those shapes vary. A path element has a method called getTotalLength() which lets you know how long the path is. That’s pretty cool and sometimes useful, but you can’t only do it on a <path>, no other element.

One reason you might want to know that length is because you intend to animate it so that the shape “draws itself” – a cool little design effect (collection of examples). You can do it in CSS, but it’s nice to use some JavaScript to apply that CSS so it animates the perfect distance every time.

So say you want to do that drawing effect, but the shape is a <polygon> so the JavaScript fails. You can turn that polygon into a path, without changing it visually, by simply adding a point to it that has bezier handle. As in, click with the Pen tool and drag so the handles come out and align the handles right along the line that’s already there. The existence of that point will make it a <path> in output.

If you do this a lot, there is a tool called Poly2Path that works, and doesn’t require that superfluous point.