Drawing SVG Paths

October 10, 2014

SVG is versatile and scalable. Let’s animate it.

SVG path animations are derived from the manipulation of two important style attributes, stroke-dasharray & stroke-dashoffset. stroke-dasharray defines the width and spacing of your path dashed line. stroke-dashoffset defines the beginning point of your dashes. To draw your SVG, you effectively set stroke-dasharray to the length of your path element, and animate the stroke-dashoffset to appear as if it is drawing the line.

There are two important things to know here, 1) this solution is based on CSS3 transformations so you have to be ready for cross-browser compatibility issues, and 2) I learned all of this from Jake Archibald’s post, where you can learn a ton more about how this is actually working.

Here’s the function I’ve been using, and you can manipulate it accordingly. I recommend reading the post above, along with Jake’s post about web animations at Smashing Magazine, which explains the different approaches to animating objects on your screen with and without javascript.

function animatePath()

Draw It!

function animatePath(id, duration) {
  var path = document.querySelector('#'+id+' path');
  var length = path.getTotalLength();
  path.style.transition = path.style.WebkitTransition = 'none';
  path.style.strokeDasharray = length + ' ' + length;
  path.style.strokeDashoffset = length;
  path.style.transition = path.style.WebkitTransition = 'stroke-dashoffset \
                          ' + duration + 'ms ease-in-out';
  path.style.strokeDashoffset = '0';

// execute the function
animatePath('dash', 3000);
⤎ back to posts