LoginSignup
0
0

More than 1 year has passed since last update.

かんたん慣性スクロール ver.2 GSAP ScrollSmoother.js ぽいのを実現するメモ

Last updated at Posted at 2023-03-07

GSAPScrollSmoother.jsはブラウザネイティブのスクロールバーで慣性スクロールを実装できるライブラリですが、同じようにブラウザネイティブのスクロールバーで実装出来ないか試したものです。

デモ

Windowsのマウスホイールでもなめらかな余韻の残る慣性スクロールになっています。
MacのTrackPadに近しいスクロール感覚だと思います。

See the Pen Untitled by ONSEN (@TaroTsujimoto) on CodePen.

コード

マウスホイールに特化した実装でMacのトラックパッドで実行すると、命令が走りすぎて不具合が発生するため、Macのトラックパッドの場合は実行されないようにしています。

GSAPの ScrollToPlugin と組み合わせて使います。
スクロールの出だしが10px以下だと1.5秒間トラックパッドだと判定し、
それ以外だとマウスホイールと判定してScrollToPlugin で wheelDeltaY 分だけスクロールさせています。

ScrollSmoother.js は指定された要素#smooth-wrapper #smooth-contentなどでコンテンツを囲ってやる必要がありますが、この方法では必要ありません。

import gsap from 'gsap';
import { ScrollToPlugin } from 'gsap/all';
gsap.registerPlugin(ScrollToPlugin);

let ignitionTimeoutID;
let isWheel = true;
let isTrackPad = false;

document.querySelector('body').addEventListener('mousewheel', disableScroll, { passive: false });

function disableScroll(e) {
  const wheelDeltaY = e.wheelDeltaY;
  if (isWheel) e.preventDefault();

  // スクロールの出だしが10px以下だと1.5秒間トラックパッドと判定する
  if (Math.abs(wheelDeltaY) < 10) {
    isWheel = false;
    isTrackPad = true;

    clearTimeout(ignitionTimeoutID);
    ignitionTimeoutID = setTimeout(() => {
      isTrackPad = false;
    }, 1500);
  } else {
    if (!isTrackPad) {
      isWheel = true;

      let direction = `-=${Math.abs(wheelDeltaY)}px`;
      if (wheelDeltaY < 0) direction = `+=${Math.abs(wheelDeltaY)}px`;
      gsap.to(window, {
        scrollTo: { y: direction, autoKill: false },
        duration: 1,
        ease: 'power2.out',
      });
    }
  }
}
0
0
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
0
0