Scalable Vector Graphics (SVG) have held a number of key roles in advancement of front-end web development over the last few years. The core advantages of SVGs bring eliminating pixelation in simple graphics and bringing a number of dynamic and accessibility features to images that are a normally static form of media. However, SVGs also offer a form of image that allows developers to manipulate their contents and presentation with standard styles and scripts.
One major advantage of being able to modify the presentation aspects of an SVG is the ability to simulate the drawing of shapes by manipulating their shapes and line paths.
How animated path drawings work
The fundamental concept behind animating a path in SVG starts with drawing a line (or stroke) along a shape. Leveraging the ability to create dashed line styles we can create dashes and gaps in these dashes the same size as the total line length we’re looking to draw out.
stroke-dasharray CSS property creates a dashed line which we can move back and forth along our path using
stroke-dashoffset. In reality we’re just moving a dashed line pattern but as we only see a segment of this pattern at a time it appears to draw into view.
Basic CSS example
In this basic example, the path now follows a shape instead of a simple line and CSS transitions are used to smoothly animate the visible line into place. Graduating from basic lines and rectangles requires the use of the
Setting the current
document.getElementById('.path-selector').style.strokeDashoffset = 100;
Animating complex shapes and text
As the complexity of the shapes and paths grows so does the need to carefully curate the SVG contents. Programs like Adobe Illustrator and XD offer the ability to create and export images as SVG but may sometimes compress a path you intended to animate into something else. Elements like text or grouped shapes need to be converted to solid shape outlines before you can add animated outlines.
It’s critical that designers and developers work closely together to make sure that the final exported SVG not only looks good but is built in a format that lets a developer extend it into the final animation in the browser.
Current limitations and future technology
Animated SVG paths are supported in all major browsers at the moment (including Internet Explorer 11) so the scope for using this approach in your next project is rather forgiving.
However, the main limitation for this technique is that each animation can take some time to set up and develop due to the tedious nature of working out individual path lengths and calculating when and how to manipulate them.
Thankfully an updated specification for SVG is slowly working its way into browsers that allows the path length to be manually set for each shape using the
pathLength attribute. This opens up the ability to focus less on the specification of the image and more on how it’s presented and animated.