Portfolio BLog: C5log

GSAPのScrollTriggerと連動するコード

GSAPライブラリに追加して、ScrollTriggerを読み込む。

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.5/ScrollTrigger.min.js"></script>

gsap.registerPlugin(ScrollTrigger); // ScrollTriggerの初期化

スクロールで発火するコード

const lottie1 = document.querySelector('.lottie1');
const animation1 = lottie.loadAnimation({
  container: lottie1,
  // 略
});

// scrollTriggerで発火する
ScrollTrigger.create({
  trigger: lottie1,
  start: "top 40%",  // Lottieアニメーション開始位置
  onEnter: () => animation1.goToAndPlay(0, true),
  markers: true  // テスト用マーカー
});

スクロールと連動するコード

const lottie2 = document.querySelector('.lottie2');
const animation2 = lottie.loadAnimation({
  container: lottie2,
  // 略
});

gsap.from(lottie2, {
  // 現れ方をお好みで設定
  x: -200,
  opacity: 0,
  // scrollTriggerでスクロールと連動する
  scrollTrigger: {
    trigger: lottie2,
    start: "top 40%",
    end: "+=500",  // Lottieアニメーションが終了するまでのスクロール量
    onUpdate: (scroll) => {
      const scrollRatio = scroll.progress;  // 現在のスクロール割合(0〜1)
      const totalFrames = animation2.getDuration(true);  // Lottieの総フレーム数
      animation2.goToAndStop(scrollRatio * totalFrames, true);  // 現在のスクロール割合に応じたフレームに移動
    },
    markers: true,
    scrub: true,
  },
});