WEB

【Javascript】GSAPを使用して背景を固定する方法

はじめに

GSAPのScrollTriggerを使用して、スクロールに応じて背景を固定する方法を解説します。

やりたいこと

スクロールすると、背景のロゴが出現し、メインビジュアルが見えなくなったタイミングで背景を固定します。

準備

必要なライブラリ

今回使用するライブラリは以下の2つです

  • GSAP: アニメーションライブラリ
  • ScrollTrigger: GSAPプラグインで、スクロール操作に基づいたアニメーションを実現します

HTMLに以下スクリプトを設置します。

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

 

実装方法

1. HTML

背景を固定する要素とコンテンツを配置します。

<body>
  <!--HEADER-->
  <header class="header">
    ヘッダー
  </header>
  <!--/HEADER-->
  <!--MAIN-->
  <main>
    <section>
      <div class="main-visual">
      </div>
    </section>
    <div id="fixed-wrap">
      <div id="fixed-bg"></div>
      <section class="section">
        <div class="inner">
          Section01
        </div>
      </section>
      <section class="section">
        <div class="inner">
          Section02
        </div>
      </section>
      <section class="section">
        <div class="inner">
          Section03
        </div>
      </section>
      <section class="section">
        <div class="inner">
          Section04
        </div>
      </section>
    </div>
  </main>
  <!--/MAIN-->
  <!--FOOTER-->
  <footer class="footer">
    フッター
  </footer>
  <!--/FOOTER-->
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js"></script>
  <script type="text/javascript" src="/js/script.js"></script>
</body>
 

2. CSSで背景を設定

CSSで背景画像の位置やスタイルを定義します。
※装飾のCSSは省略しています

#fixed-wrap {
  position: relative;
  height: 100%;
}
#fixed-bg {
  position: absolute;
  top: 0;
  left: 50%;
  transform: translate(-50%, 0);
  z-index: -1;
  background-image: url("/logo.png");
  background-repeat: no-repeat;
  background-size: 700px auto;
  background-position: top;
  width: 100%;
  height: 100%;
  max-height: 700px;
  opacity: 0.05;
}
#fixed-bg.is-active {
  position: fixed;
  bottom: 0;
  top: auto;
  left: 50%;
}

 

3. JavaScriptでScrollTriggerを設定

GSAPとScrollTriggerを使用して背景がスクロール時に固定されるように設定します。

document.addEventListener("DOMContentLoaded", () => {
// ScrollTriggerプラグインを登録
gsap.registerPlugin(ScrollTrigger);

// ScrollTriggerの設定
ScrollTrigger.create({
trigger: "#fixed-bg",
start: "bottom bottom",
endTrigger: "#fixed-wrap",
end: "bottom top",
toggleClass: { targets: "#fixed-bg", className: "is-active" },
});
});

 

ポイント


※markers: true,にするとマーカーが表示され理解しやすいです!

  • trigger: アニメーションのトリガーとなる要素(#fixed-bg)
  • start: アニメーション開始位置を指定(bottom bottom)
  • endTrigger: アニメーションが終了する要素(#fixed-bg)
  • end: アニメーション終了位置を指定(bottom top)
  • toggleClass: クラスの追加・削除でスタイルを制御

#fixed-bgの下部が画面下に達したときに、#fixed-bgにクラスis-activeが追加になるので、position: fixed;が適用され、背景が固定されます。
また、#fixed-wrapの下部が画面下に達したときに、アニメーションが終了するのでクラスis-activeが削除されます。

参考サイト

こちらのサイトを参考にさせていただきました。

 

N.T
平日はコーディング、週末は子供と公園を走り回っています。