user4821826
user4821826

Reputation: 129

javascript loop through svg animation

I am having some issues with looping SVG animations.

I figured out how to animate paths, but the problem is that I want them disappear when they are drawn and after a short delay of time show different two ones. I need those two operations to be looped as well.

www.jsfiddle.net/8zneofyw/

Thanks

Upvotes: 0

Views: 631

Answers (1)

Persijn
Persijn

Reputation: 15000

Challange accepted

This is how i solved it:

  • Animations run for 10s.
  • Each path has a line and an equally long whitespace stroke-dasharray: 160, 160;

So this creates an empty line that gets drawn.

But with that all four paths are created at the same time and we want to draw two and two lines. So we need an delay of 5 second between the first two paths and the second two:

  • Add white space after the path to fill half the animation: stroke-dasharray: 160, 160, 0, 320;
  • Now we just need to start the animations at the right time: stroke-dashoffset: 160; for the first two. and stroke-dashoffset: 320 for the last two.

path {
  stroke-width: 2;
}
#one {
  stroke-dasharray: 160, 160, 0, 320;
  stroke-dashoffset: 160;
  animation: magic 10s linear infinite;
}
#two {
  stroke-dasharray: 160, 160, 0, 320;
  stroke-dashoffset: 160;
  animation: magic 10s linear infinite;
}
#tree {
  stroke-dasharray: 165, 165, 0, 330;
  stroke-dashoffset: 330;
  animation: moremagic 10s linear infinite;
}
#four {
  stroke-dasharray: 165, 165, 0, 330;
  stroke-dashoffset: 330;
  animation: moremagic 10s linear infinite;
}
@keyframes magic {
  0% {
    stroke-dashoffset: 160;
  }
  50% {
    stroke-dashoffset: 0;
  }
  50.01% {
    stroke-dashoffset: -160;
  }
  100% {
    stroke-dashoffset: -160;
  }
}
@keyframes moremagic {
  to {
    stroke-dashoffset: 0;
  }
}
<svg height="200px" viewBox="0 0 200 100">
  <circle cx="25" cy="50" r="10" fill="none" stroke="tomato" />
  <circle cx="175" cy="50" r="10" fill="none" stroke="pink" />
  <path id="one" d="m25,50, 150,0" fill="none" stroke="green" />
  <path id="two" d="m25,50, 75,20 75,-20 " fill="none" stroke="blue" />
  <path id="tree" d="m25,50, 75,-20 75,20 " fill="none" stroke="firebrick" />
  <path id="four" d="m25,50, 75,-30 75,30 " fill="none" stroke="aqua" />
</svg>

Upvotes: 2

Related Questions