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) {

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">
  <!-- 👇 -->
    stroke="currentColor" />

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.