Creating SVG line drawing animations

May 7, 2015

Recently, I came across a very nice page on the Square Space site while surfing the web. The page features some nice animations. which improve the user experience. The animations are implemented with the Scrollr jQuery plugin, an elegant way of performing scroll based page animations. However, what caught my eye was the SVG line animation. Having stayed away from SVG usage, mainly because of inconsistent browser support, I got curios and decided to build a small test case. Here is what I learned along the way:

How to animate a SVG line drawing?

There are several very good sources about SVG line animation on the web already so here is my summaryt of it.

Looking at animated SVG line drawings, it seems that the length of the individual lines is animated from zero to full length. I was surprised to learn that you cannot animate the length of a line, or a path, at all. Turns out that we can create the illusion of animating the line length by using the stroke-dash property of a SVH path. These two blog posts explain this expertly:

Using requestAnimationFrame instead of using an interval timer

While the animation that got me started was scroller based, these two blog posts take different approaches to implement the animation. Jake Archibald uses CSS3 transitions and he reveals a little trick ( Using getBoundingClientRect to trigger layout ) along the way, while the Vox blog post uses a Javascript based approach. Furthermore, the Vox implementation uses requestAnimationFrame, a more efficient way of building Javascript based animations. Paul Irish provided an early introduction “requestAnimationFrame for Smart Animating” in 2011. At the time the spec wasn’t finished and browser support was just not there. Today, browser support has much improved , even IE supports it for version 10 and above. For older browsers there are polyfills that emulate requestAnimationFrame functionality with an interval timer. If you still build stuff for older browsers you might want to consider Oleg Slobodskoi’s polyfill AnimationFrame.js.

Knowing the mechanics of animating SVG lines I started out to build my test case. I fired up Adobe Illustrator and created three rectangular shapes and saved them as .svg files.

To get the svg code, click Show SVG Code… in the SVG Options modal window and you’ll see the code in another modal text window.

Note: If you create simple shapes like a rectangle or circle , the svg code will describe them as basic shapes and not as paths and that will not work. So to convert a basic shape into a compound path just select the shape and go to Object > Compound Path > Make or hit Command + 8 (on a Mac).

There is one more thing to do before we are finished. We need to make the svg line drawing responsive. Again, there are plenty of resources on the web about this subject.

Below you can see what this test case looks like

Start Animation