Skip the Measurement: Normalize SVG Path Length for Line-Drawing Animation

The standard technique for drawing a line with SVG is to use a <path> with a stroke, give it a stroke-dasharray matching the path's length, and push a stroke-offset far enough out that the stroke is hidden. Animating that offset back to 0 makes the shape appear to draw itself.

The awkward part is learning the path's length. In JavaScript you can select the element and call pathEl.getTotalLength(), but the result is usually an odd decimal, and CSS offers no equivalent.

A friendlier approach is to set the length instead of measuring it:

<path d="M66.039,133.545 ... " pathLength="1" />

On its own this appears to change nothing — the entire path still renders as before. The difference is that the path's internal length math now treats the length as 1.

With that in place, stroke-dasharray can be set to 1, and the offset animated purely in CSS:

.path {
  stroke-dasharray: 1;
  stroke-dashoffset: 1;
  animation: dash 5s linear alternate infinite;
}

@keyframes dash {
  from {
    stroke-dashoffset: 1;
  }
  to {
    stroke-dashoffset: 0;
  }
}

The technique was passed along by Adam Haskell, who emailed about it a few months before publication.