Go to homepage

Projects /

January 19, 2021

Self-Drawing SVG Animation

By CodyHouse
404 HTML, CSS, JS components. Download →

How to create a self-drawing SVG animation in CSS.

To create a self-drawing SVG animation, you need to:

  1. Set the stroke-dasharray and stroke-dashoffset values equal to the path length;
  2. Animate the stroke-dashoffset value from the path length to 0.
svg > * { /* SVG <path> */
  --path-length: 367;
  stroke-dasharray: var(--path-length);
  stroke-dashoffset: var(--path-length);
  transition: stroke-dashoffset .5s;
}

svg:hover > * {
  stroke-dashoffset: 0;
}

By increasing the stroke-dasharray value, you're replacing the stroke with a pattern of dashes and gaps. The higher the stroke-dasharray value, the higher the length of the gaps and dashes. You'll need to increase this value (stroke-dasharray) to the point where no gap is visible and you have only one dash (dash length = path length).

The stroke-dashoffset value, on the other hand, is used to offset (i.e., translate) the dash. By setting it equal to the path length, the dash disappears.

Optionally, you can get the path length in JavaScript:

(function() {
  var svgObj = document.getElementsByClassName('self-draw-anim__obj');
  if(svgObj.length > 0) {
    console.log(svgObj[0].getTotalLength());
  }
}());

The .self-draw-anim__obj class in the code example above is applied to the SVG path you want to animate:

<svg class="self-draw-anim__decoration" viewBox="0 0 156 40" preserveAspectRatio="none" aria-hidden="true">
  <!-- 👇 -->
  <path 
    class="self-draw-anim__obj"
    d="M77.867,1.875l-59.314,13.4C13.5,16.418,8.184,17.689,4.406,21.139c-1.421,1.3-2.631,3.081-2.37,4.956A5.586,5.586,0,0,0,3.49,28.908c2.143,2.449,5.293,3.852,8.445,4.847A73.518,73.518,0,0,0,27.41,36.55c8.793.8,17.637.89,26.469.975q20.22.2,40.44.378a179.741,179.741,0,0,0,21.225-.657c7.9-.87,15.638-2.778,23.345-4.681,3.058-.755,6.19-1.542,8.785-3.282s4.584-4.66,4.261-7.7c-.5-4.659-5.718-7.245-10.311-8.717C117.7,5.2,92.044,4.657,66.842,4.365,54.984,4.228,43.011,4.14,31.413,6.534"
    fill="none"
    stroke-miterlimit="10"
    stroke="currentColor" />
</svg>

If you don't want the SVG to preserve its aspect ratio (set in the viewbox), apply preserveAspectRatio="none" to the SVG element. In the demo below, for example, the SVG adapts to the size of the text.

Live example:

Project duplicated

Project created

Globals imported

There was an error while trying to export your project. Please try again or contact us.