つれづれなる備忘録

日々の発見をあるがままに綴る

ブログデザイン備忘録 ~ スクロールに連動するアニメーション

前回の記事

atatat.hatenablog.com

でAnimistaを紹介したが、今回は本来のスクロールに連動するアニメーションを実装を紹介したい。前回同様に以下のColissの記事のコードを利用しつつ、アニメーション動作は前回Animistaで生成したバウンス動作を使用する。

coliss.com

動作としてはスクロールで画面にオブジェクトがあらわれたらアニメーションを一度だけ実行する。一度スクロールアウトして再びスクロールで画面に戻すと、またアニメーションを開始する。

前回との違いは、CSSセレクタを用いてクラスごとにキーフレームアニメーションを割り当てていたが、今回はhtmlに記述する。

具体的には、以下のCSSコードを削除またはブランクにして

.card h2 {
        /* タイトルのアニメーション、左から右にフェードイン */
    animation: animTitle 2s infinite;
} 

CSSに記述する代わりにhtml中に

 <h2 class="animate" data-animate="animTitle 2s ">Profile picture</h2>

と記述して、data-animateでキーフレームアニメーションの名称と実行時間を指定する。

次にjavascriptでスクロールイン/アウトを監視して、アニメーションを開始する関数を記述する。

スクロールイン/アウトを監視する部分は

let observer = new IntersectionObserver(callback);

        const animationItems = document.querySelectorAll('.animate');

          animationItems.forEach(item => {
            observer.observe(item)         
        })

アニメーションを開始する部分は

  const callback = (entries) => {

            entries.forEach(
                (entry) => {
                    if (entry.isIntersecting) {
                        console.log("The element is intersecting >");       
                        entry.target.style.animation = 
                        entry.target.dataset.animate;
                    } else {
                        entry.target.style.animation="none";
                    }
                }
            );       
        }

詳細は スクロールに連動するアニメーションを実装する時は、JSのIntersection Observerを使用すると簡単に実装できる | コリス を参照。

実行例は以下の通り

See the Pen anim_scroll2 by ATATAT (@atatat) on CodePen.