惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tailwind CSS Blog
The GitHub Blog
The GitHub Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
B
Blog
Microsoft Security Blog
Microsoft Security Blog
Stack Overflow Blog
Stack Overflow Blog
量子位
Martin Fowler
Martin Fowler
月光博客
月光博客
P
Proofpoint News Feed
博客园_首页
Y
Y Combinator Blog
I
InfoQ
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
Visual Studio Blog
H
Help Net Security
U
Unit 42
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 司徒正美
MongoDB | Blog
MongoDB | Blog
F
Fortinet All Blogs
罗磊的独立博客
酷 壳 – CoolShell
酷 壳 – CoolShell

Ben Frain

Well done AI, that’s the end of the honest boxes The Beginnings, by Rudyard Kipling So, you want a React modal that uses the <dialog> element and transitions in AND out? Scroll indicators on tables with background colours using animation-timeline Review: SoundPEATS Clip1 Open ear clip-on headphones VS Code – highlight just the active indent guide Review: MoErgo Go60, a split ergonomic and fully programmable keyboard Review: Kinesis mWave mechanical ergonomic and programmable keyboard iOS26 Safari theme-color/tab-tinting with fixed position elements is a mess New Book: Responsive Web Design with HTML5 and CSS, 5th Edition Use @supports with a proxy feature/value for features you can’t test for (@starting-style) First adventures in View Transitions Review: Benq Screenbar Pro and Halo lightbars. The kit you never knew you needed! Center items in a container, and make then left aligned when they overflow A single element CSS donut timer/countdown timer, that can sit on any background Review: Open Ear Headphones – Bose Open Ultra v Huawei FreeClip In search of the perfect autocomplete for CSS Managing multiple versions of node, without NVM or additional tools Review: Keychron Q14 Max Alice 96 Key mechanical keyboard NEW VIDEO COURSE: Responsive Web Design with HTML5 and CSS Is CSS Grid really slower than Flexbox? Review: Advantage360 Pro Signature Edition 2024 mechanical ergonomic keyboard More Keys or Fewer Keys for mechanical keyboards Yes! You can use position: sticky and overflow together Neovim – how to do project-wide find and replace? Review: Keyboardio Model 100, split, wooden, mechanical keyboard Struggling to learn SwiftUI How to create rounded gradient borders with any background in CSS How to get equal size icons in the cmp completion menu of Neovim with Kitty terminal Review: Dygma Defy, split, mechanical, programmable ergonomic keyboard
What’s the best way to reset WAAPI chained animations?
Ben Frain · 2023-12-21 · via Ben Frain

There are often times where I want to reset a sequence of chained animations I have made using WAAPI.

Here is a reduction:

See the Pen How to reset chained animations? by Ben Frain (@benfrain) on CodePen.

I’m using WAAPI to run a series of animations. My reduction moves the box to the right, waits three seconds, then moves the circle to the right.

What I would like to do, is ‘reset’ that chained animation at any point after the first has started playing. Both elements should return to their starting position and start the sequence again.

But that, just that, can seem very hard to accomplish.

Demonstrating the problem

The problem is most obviously seen if waiting for the circle to start moving and then click “Play/Restart”. When you do that, although the function is fired, nothing happens. If you wait for the sequence to end, and then click, it runs again but the circle does not go back to its starting position until the square gets to end, which makes sense as we are filling in both directions, so that circle is doing as it has been told! We just animated it to the right, and that was the last thing we told it.

Make a sequence to reverse the animations?

The next place my mind went to to solve this, was creating a ‘reset’ sequence, that ‘animates’ the relevant elements back to their starting position over 0 time. And then run the original animations again. But that was just one part of the solution. I found it was necessary to deal with cancelling any animations that has already started. So, to solve I had a reverseAnimations() function that included this at the top:

const animatingElements = document.getAnimations({
  subtree: true,
});
if (animatingElements.length > 0) {
  animatingElements.map((item) => {
    item.cancel();
  });
}

So, where are we up to at this point? In order to reset our sequence I was thinking I needed to cancel any running animations, and then run a bunch of animations to reset the elements, before running the main animations again. For these two elements alone, the code needed now looks like this:

const CIRCLE_REVERSE = CIRCLE.animate(
  {
    transform: "translateX(150px)",
  },
  {
    duration: 0,
    fill: "both",
    direction: "reverse",
  }
);
CIRCLE_REVERSE.pause();

const BOX_REVERSE = BOX.animate(
  {
    transform: "translateX(500px)",
  },
  {
    duration: 0,
    fill: "both",
    direction: "reverse",
  }
);
BOX_REVERSE.pause();

function reverseAnimations() {
  // First cancel anything animating
  const animatingElements = document.getAnimations({
    subtree: true,
  });
  if (animatingElements.length > 0) {
    animatingElements.map((item) => {
      item.cancel();
    });
  }
  // Now reverse the effect with dedicated methods
  CIRCLE_REVERSE.play();
  BOX_REVERSE.play();
}

This works, you can try it using the ‘Reverse and Play’ button. But seems like a lot of effort, no? Well, turns out the ‘secret sauce’ to solving this more economically is already there, but before we get to that, another method I considered was reverse().

What about reverse()?

You can also try reverse(). In this instance, I am first updating the playback rate of the animation to make it seem instant with updatePlaybackRate(1000) and then using reverse() to play the animation back to the beginning, and then using a finished.then() promise to reset the playback rate to ‘normal’ with updatePlaybackRate(1). This works well enough if the sequence finishes first, but if not, it reverses the direction any running animation the opposite way (clues in the title ;)). Try playing the animation and then clicking ‘Reverse’ in the example when the square starts to move and the square will go back to the beginning (good) but the circle will jump to the end (bad).

So, what’s the simplest way to do this?

Our little snippet above, to kill off any existing animations is so effective, we don’t need to use something to reverse the effects, as at this point they no longer exist. Instead, we can now just re-run our original animation. When you click the ‘Cancel’ button in the reduction, this is what happens:

CANCEL.addEventListener("click", () => {
  const animatingElements = document.getAnimations({
    subtree: true,
  });
  if (animatingElements.length > 0) {
    animatingElements.map((item) => {
      item.finish();
      item.cancel();
    });
  }
  runAnimations();
});

You can click Cancel at any point in the sequence and it will behave as expected. It first finds any animations, cancels their effects (I am running getAnimations on the document but you can narrow its scope), and then runs our animations by calling our function that runs our original sequence.