Home > OS >  How to remove animation from HTMLElement
How to remove animation from HTMLElement

Time:11-07

I'm building an animation tool that uses Web Animations API, the problem that I have is that every time I play the animation, I'm actually creating a new animation, so if I do console.log(el.getAnimations()) it will return an array with multiple animations, but I'm using only the last one, and this of course is wasting a lot of memory. How can I reuse or delete the first animation?

To animate elements I do this:

 function play(){
       el?.animate(el.kfs, {
        duration: duration.value,
        delay: -currentTime.value,
        iterations: Infinity,
        composite: "replace",
    })
}

and to pause the animation I do this:

function pause(){
  el?.getAnimations().forEach(anim => anim?.pause()
}

Here is a simple working example:

const el = document.getElementById('el')

function playAnim(){
  el.animate(
  [{backgroundColor:'red'}, {backgroundColor:'black'}],
  {
      duration: 1000,
      iterations: Infinity
   })
 }
 
 playAnim()
 el.getAnimations()[0].pause()
 playAnim()
 console.log(el.getAnimations().length) // will output 2
<div id="el">el</div>

CodePudding user response:

const el = document.getElementById('el');
const kfs = [{backgroundColor:'red'}, {backgroundColor:'black'}];

function playAnim(){
  let anim = el.getAnimations()[0];
  if(anim){
    let eff = anim.effect;
    eff.setKeyframes(kfs);
    anim.play();
  }else{
    el.animate(kfs,
    {
        duration: 1000,
        iterations: Infinity
     });
   }
 }
 
 playAnim()
 el.getAnimations()[0].pause()
 playAnim()
 console.log(el.getAnimations().length)
<div id="el">el</div>

I have solved it, the way to do this is to get the animation, then get the keyframeEffect of the animation, and use the setKeyframes method, then play the animation.

Still out of curiosutiy I'd like to know if there is a way to delete an animation because I havent found it.

CodePudding user response:

Sounds like you are not willing to "pause" the animation but to "cancel" it. For this, use the cancel() method.

const el = document.getElementById('el')

function playAnim(){
  el.animate(
  [{backgroundColor:'red'}, {backgroundColor:'black'}],
  {
      duration: 1000,
      iterations: Infinity
   })
 }
 
 playAnim()
 el.getAnimations()[0].cancel()
 playAnim()
 console.log(el.getAnimations().length) // will output 2
<div id="el">el</div>

  • Related