Reverse css keyframe animation

Asked by At

I've written a css animation using keyframes for svg path

path {
  animation: anim 1s linear;
  animation-fill-mode: forwards;
}

@keyframes anim {
  50% {
    d: path('M20 20 L 20 20');
  }
  100% {
    d: path('M10 10 L 30 30');
  }
}
<path class="top" d="M10 10 L 30 10" stroke-width="2" stroke="black" fill="transparent" />

Source

If you click on the svg you can see the animation in action. Now, if you click again I want it to animation to its original state. I've tried adding

transition: all 1s ease-out;

and

animation-direction: alternate;

But still there is no animation back to its initial state.

So the question is, how can I animate back?

1 Answers

4
Temani Afif On Best Solutions

With transition you can easily do this but the animation will be slightly different:

const svg = document.querySelector('svg');

svg.addEventListener('click', () => {
  svg.classList.toggle('close');
});
svg {
  border: 1px solid blue;
}

svg path {
  transition: 0.2s all linear;
}

svg.close path.top {
  d: path('M10 10 L 30 30');
}

svg.close path.middle {
  d: path('M20 20 L 20 20');
}

svg.close path.bottom {
  d: path('M10 30 L 30 10');
}
<svg width="190" height="160" xmlns="http://www.w3.org/2000/svg">

  <path class="top" d="M10 10 L 30 10" stroke-width="2" stroke="black" fill="transparent"/>
  <path class="middle" d="M10 20 L 30 20" stroke-width="2" stroke="black" fill="transparent"/>
  <path class="bottom" d="M10 30 L 30 30" stroke-width="2" stroke="black" fill="transparent"/>
</svg>

Another idea is to rely on animationiteration where the trick is to run an infinite animation and you stop it on each iteration.

const svg = document.querySelector('svg');

const path = document.querySelector('svg path');

svg.addEventListener('click', () => {
  svg.classList.toggle('close');
});


path.addEventListener('animationiteration', () =>{
 svg.classList.toggle('close');
});
svg {
  border: 1px solid blue;
}


path.top {
  animation: close-top 0.2s linear infinite alternate;
}

path.middle {
  animation: close-middle 0.2s linear infinite alternate;
}

path.bottom {
  animation: close-bottom 0.2s linear infinite alternate;
}

svg:not(.close) path {
 animation-play-state: paused;
}

svg.close path {
 animation-play-state: running;
}

@keyframes close-top {
  50% {
    d: path('M20 20 L 20 20');
  }
  100% {
    d: path('M10 10 L 30 30');
  }
}

@keyframes close-middle {
  to {
    d: path('M20 20 L 20 20');
  }
}

@keyframes close-bottom {
  50% {
    d: path('M20 20 L 20 20');
  }
  100% {
    d: path('M10 30 L 30 10');
  }
}
<svg width="190" height="160" xmlns="http://www.w3.org/2000/svg">

  <path class="top" d="M10 10 L 30 10" stroke-width="2" stroke="black" fill="transparent"/>
  <path class="middle" d="M10 20 L 30 20" stroke-width="2" stroke="black" fill="transparent"/>
  <path class="bottom" d="M10 30 L 30 30" stroke-width="2" stroke="black" fill="transparent"/>
</svg>