Giacomo Cerretini
Giacomo Cerretini

Reputation: 59

How to animate svg dotted line from one point to another?

I want to understand how to animate like this:

PIC1

PIC2

PIC3

I have this svg code (x1,x2,y1,y2 are dynamic assignment)

<svg id={props.id} class="connect" width="100%" height="100%" viewBox="100%">
   <line lass="path_in" x1={x1} y1={y1} x2={x2} y2={y2} stroke="#5184AF" stroke-width="5" stroke-linecap="round" stroke-dasharray="1, 10"/>
</svg>

I try this:

svg .path_in {
    stroke-dasharray: 1300;
    animation: dash 4s linear;
    -webkit-animation: dash 4s linear;
  }
  @keyframes dash {
    from {
      stroke-dashoffset: 1300;
    }
    to {
      stroke-dashoffset: 0;
    }
  }
  @-webkit-keyframes dash {
    from {
      stroke-dashoffset: 1300;
    }
    to {
      stroke-dashoffset: 0;
    }
}

Upvotes: 3

Views: 627

Answers (1)

enxaneta
enxaneta

Reputation: 33054

One way to animate it would be using SMIL animations like this:

svg{border:1px solid}
<svg viewBox="0 0 100 50">
   <line lass="path_in" x1="10" y1="25" x2="10" y2="25" stroke="#5184AF" stroke-width="5" stroke-linecap="round" stroke-dasharray="1, 10">
    <animate 
       attributeName="x2"
       attributeType="XML"
       from="10" to="90"
       dur="4s"
       repeatCount="indefinite"/>
   </line>
</svg>

In this demo the <animate> element is animating the x2 attribute from="10" (the same value as x1) to="90". The animation's duration is 4 second: dur="4s"

Observation: you don't need width="100%" since if you don't declare the width and height of the svg element by default will take all the available width.

Upvotes: 3

Related Questions