1
1
はじめての記事投稿
Qiita Engineer Festa20242024年7月17日まで開催中!

JavaScriptで複数のアニメーションを連続させる方法

Posted at

業務で10連ガチャのアニメーション演出をSCSS、JavaScriptで実装する機会があり、その時に使用したテクニックをまとめました。

大まかに言うと、CSSのanimationプロパティとJavaScriptのanimationendイベントを使用します。

.fade-in {
  animation: fadeIn 2s liner 0s forwards running;
}

.spin {
  animation: spin 2s liner 0s forwards running;
}


@keyframes fadeIn {
  0% { opacity: 0; }
  100% { opacity: 1; }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
const targetElement = document.querySelector('.hoge');
hoge.addEventListener('animationend', (e) => {
    const animationName = e.animationName;
    switch(animationName){
        case 'fadeIn':
            // 要素が回転するアニメーション付与
            targetElement.classList.add('spin')
            break;
        case 'spin':
            console.log('アニメーション終了')
            break;
    }
});

①アニメーションを適用させたい要素を取得
②animationendイベントで各アニメーションの終了を検知
③switch文で終了したanimationNameごとに処理を振り分ける(例では次に適用したいanimationのクラス名を付与)

といったやり方により、アニメーションを連続させることができました。

③ではクラスを付与して次のアニメーションを表示させていますが、CSS側で

.hoge { animation-play-state: paused; }

を予め指定しておいてから、Javacript側で

targetElement.animationPlayState = 'running';

のようにanimation-play-stateを実行中に変えてあげる、という方法でも実現できるかと思います。

※例ではquerySelectorを使用していますが、他の方法でDOMを取得した方が良いかもしれません(Vue.jsならref属性と$refsを使うなど)。
コンポーネント外でもhogeクラスを使っている場合、querySelectorやquerySelectorAllを使うと意図していないhogeクラスを持つDOMを取得する可能性があるためです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1