Animating SVG Paths with CSS stroke-dashoffset

The self-drawing SVG path effect is a popular web animation technique created by manipulating two CSS properties: stroke-dasharray and stroke-dashoffset. By sizing a stroke’s dashes and gaps to match the exact length of an SVG path, developers can offset the dash completely out of view and then transition that offset back to zero. This process progressively reveals the stroke along the vector coordinates, producing a smooth illusion of the shape being drawn in real time.

The Foundation: stroke-dasharray and stroke-dashoffset

To understand the animation technique, you must understand how SVG strokes handle dashes:

How the Drawing Mechanism Works

The animation relies on a four-step sequence:

  1. Calculate Path Length: Determine the exact pixel length of the SVG path. In JavaScript, this is done using the SVGPathElement.getTotalLength() method.
  2. Create a Full-Length Dash: Set stroke-dasharray to the path’s total length. At this point, the path consists of one visible line (the length of the entire path) followed by an invisible gap of the same length.
  3. Hide the Stroke: Set stroke-dashoffset equal to the total path length. This shifts the entire visible dash forward, positioning the invisible gap directly over the visible path coordinates and making the stroke disappear.
  4. Animate the Offset to Zero: Transition stroke-dashoffset from its full length value down to 0 using CSS transitions, CSS @keyframes, or JavaScript. As the offset decreases, the visible dash is pulled back across the path coordinates from start to finish.

Implementation Example

Below is a standard CSS implementation demonstrating this mechanism on a path with a total length of 500 pixels:

.drawing-path {
  stroke: #0070f3;
  stroke-width: 2;
  fill: none;
  
  /* Step 2 & 3: Set dash length and offset */
  stroke-dasharray: 500;
  stroke-dashoffset: 500;
  
  /* Step 4: Animate the offset back to 0 */
  animation: drawLine 2s ease forwards;
}

@keyframes drawLine {
  to {
    stroke-dashoffset: 0;
  }
}

Why This Technique Is Widely Used