Issue
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>
Solution
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.
And as Kaiido said, if we want delete the animation instead of replace it then using anim.cancel() would do the trick.
Answered By - imvenx Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.