Search code examples
animationsvgpath

SVG dashed path animation


How can I change the line to dashed line and still have the animation? I tried so many things but I couldn't figure it out:

svg {
  width: 100%;
  height: auto;
}
.path {
  fill: none;
  stroke: #4CAF50; /* Green color for the success path */
  stroke-width: 2;
  stroke-dasharray: 1000;
  stroke-dashoffset: 1000;
  animation: dash 5s linear forwards;
}
@keyframes dash {
  to {
    stroke-dashoffset: 0;
  }
}
<svg viewBox="0 0 100 50">
  <path class="path" d="M0,25
    Q25,10 50,25
    Q75,40 100,25"/>
</svg>


Solution

  • Assume your path is 100px long. You can make a stroke-dasharray that has 100px worth of a dashed pattern followed by a 100px (or more) gap, e.g:

    16 5 16 5 16 5 16 5 16  101
    ^-- 100px pattern ---^  ^-- At least 100px gap
    

    If you start with a stroke-dashoffset of 100, you'll only see the gap, i.e. nothing. If you then slowly animate the offset to 0, the dashed pattern will move in from the left.

    In such cases, it's is easer to tell the browser to assume the path is a given length too, rather than calculate its actual length. We can do that with the pathLength attribute.

    svg {
      width: 100%;
      height: auto;
    }
    
    .path {
      fill: none;
      stroke: #4CAF50;
      /* Green color for the success path */
      stroke-width: 2;
      stroke-dasharray: 16 5 16 5 16 5 16 5 16 101;
      stroke-dashoffset: 100;
      animation: dash 2s linear forwards;
    }
    
    @keyframes dash {
      to {
        stroke-dashoffset: 0;
      }
    }
    <svg viewBox="0 0 100 50">
        <path class="path" pathLength="100"
              d="M0,25  Q25,10 50,25  Q75,40 100,25" />
    </svg>