🕶️

emotionを使った逆再生アニメーションの実装方法について ~cssプロパティとjavascriptのanimateメソッドを比較して~

2022/05/09に公開

emoitonを使用してgsapのstaggerライクなアニメーションを実装する際に、cssプロパティで実現できることとjavascriptのanimateメソッドで実現できることに差異があったので、その一部を紹介します。

以下が分かったことです。

デモで使用しているgifはgiphy様のリンクを参照しています。
https://giphy.com/search/cowboy-bebop

デモコードをglitchに置きました。DOボタンがアニメーションのトグルになっています。

ライブデモへのリンクです
https://five-peridot-product.glitch.me

デモコードへのリンクです

https://glitch.com/edit/#!/five-peridot-product

デモ動画はloomに置いています。

デモ動画へのリンクです

https://www.loom.com/share/297c0da3462845cf800b096b60565f4a

cssプロパティのanimation-directionを使ったコードの抜粋です。
これでいけるかなと思ったのですが、うまくいかず。。。

const a = keyframes`
  0% {
    -webkit-transform: translateY(0);
    transform: translateY(0);
  }
  100% {
    -webkit-transform: translateY(-100px);
    transform: translateY(-100px);
  }
`;

...
...
...

<StyledCard
  ref={itemDomRef}
  className={cx(
  `div${n}`,
  css`
    animation-duration: ${duration};
    animation-delay: ${delay}ms;
    animation-direction: ${hide ? 'normal' : 'reverse'};
    animation-timing-function: cubic-bezier(0.25, 0.46, 0.45, 0.94);
    animation-fill-mode: both;
    animation-name: ${a};
  `
  )}
  >
</StyledCard>

次にjavascriptのanimateメソッドを使ったコードの抜粋です。
こちらだと逆再生できました。

 useEffect(() => {
    const anim = itemDomRef.current.animate(
      [
        {
          WebkitTransform: 'translateY(0)',
          transform: 'translateY(0)',
          opacity: 0,
        },
        {
          WebkitTransform: 'translateY(-100px)',
          transform: 'translateY(-100px)',
          opacity: 1,
        },
      ],
      {
        duration: duration,
        delay: delay,
        direction: hide ? 'normal' : 'reverse',
        easing: 'cubic-bezier(0.250, 0.460, 0.450, 0.940)',
        fill: 'both',
      }
    );
    return () => {
      anim.cancel();
    };
  }, [duration, delay, hide]);

少し気になったので、Web情報を探したら以下のブログを見つけました。
複雑な挙動を実装したいなら、javascriptのAPI使ってねという感じですかね。

また、WEB標準を使わないなら、ぼくの感触だとframer-motionあたりが候補ですかね。

css-vs-javascript tldr

TL;DR #
・Use CSS animations for simpler "one-shot" transitions, like toggling UI element states.
・Use JavaScript animations when you want to have advanced effects like bouncing, stop, pause, rewind, or slow down.
・If you choose to animate with JavaScript, use the Web Animations API or a modern framework that you're comfortable with.

もし、cssプロパティを駆使して逆再生できる方法を知っている人がいましたら、共有していただけると嬉しいです。

簡単ですが、以上です。

Discussion