Web Animations API — how to play backwards rather than reverse?

196 Views Asked by At

The Web Animations API has the reverse method which allows the running animation to be played back in the opposite direction it is currently headed.

However I have a scenario where I would just like to play a defined animation backwards. At present, I am accomplishing this by checking if the animation is going forwards or backwards first and then doing the opposite but this feels wonky!

Is there an established pattern for just asking a defined animation to run backwards (and not necessarily run in reverse from its current playhead)?

In code example below, if you are on the first instance (idx === 0) I check if you are going forwards by checking if playbackRate is 1 first. Without this, the animation would run backwards first.

Feels like there should be a simpler way of running an animation backwards when required — is there?

var box = document.querySelector(".thing");
var btn = document.querySelector("button");
var span = document.querySelector("span");
const move = box.animate(
    [{ transform: "translate(0px, 0px)" }, { transform: "translate(100px, 0px)" }],
    { duration: 500, fill: "both" }
);
move.pause();

let idx = 0;

function choose() {
    if (idx === 0) {
        move.playbackRate === 1 ? move.play() : move.reverse();
    } else {
        move.reverse();
    }
}

btn.addEventListener("click", () => {
    choose();
    idx = idx === 0 ? 1 : 0;
    span.textContent = idx;
});
.thing {
    width:49px;
    height: 49px;
    background-color: red;
}
<div class="thing"></div>
<button type="button">ClickMe</button>
<span>0</span>

1

There are 1 best solutions below

0
On

I believe you want the direction property, e.g.

move.effect.updateTiming({ direction: 'reverse' });