mcpField
G
gsap-scrolltrigger

gsap-scrolltrigger

github.com/freshtechbroデザイン・UI1.2k2.9k 回インストール49 週間前に更新
リポジトリ

gsap-scrolltrigger について

GSAP と ScrollTrigger を使うウェブ開発者向けのスキルです。タイムラインやスクロール連動演出、React や Three.js との連携に加え、再利用できる実装例やパフォーマンス対策を紹介します。

主な機能

  1. 01GSAP のタイムラインとトゥイーン
  2. 02ScrollTrigger による演出
  3. 03固定、パララックス、横スクロール
  4. 04React と Three.js との連携
  5. 05コード生成とタイムライン構築

活用シーン

  1. 01スクロールに応じてコンテンツを表示
  2. 02パララックスや横スクロールのページを作成
  3. 03複雑なアニメーションを順序立てて構成
  4. 04React プロジェクトのアニメーション管理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/freshtechbro/claudedesignskills --skill gsap-scrolltrigger

インストール後、Claude Code で/gsap-scrolltriggerを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

assets/easings/
easing_visualizer.html
assets/examples/
README.md
assets/starter_scroll/
index.html
main.js
README.md
style.css
references/
api_reference.md
common_patterns.md
easing_guide.md
scripts/
generate_animation.py
timeline_builder.py

詳細

GSAP と ScrollTrigger の開発

概要

GSAP(GreenSock Animation Platform)は、高パフォーマンスで本番品質のアニメーションを作成するための、業界をリードする JavaScript アニメーションライブラリです。ScrollTrigger は、スクロールに連動するアニメーションを実現する GSAP の強力なプラグインです。この 2 つを組み合わせることで、シンプルな UI トランジションから、スクロールに基づく複雑なストーリーテリング体験まで実現できます。

基本概念

基本:トゥイーン

トゥイーンとは、点 A から点 B までの単一のアニメーションです。

// Animate TO a state (from current)
gsap.to(".box", {
  x: 200,
  rotation: 360,
  duration: 1,
  ease: "power2.inOut"
});

// Animate FROM a state (to current)
gsap.from(".box", {
  opacity: 0,
  y: -50,
  duration: 0.8
});

// Animate FROM-TO (define both start and end)
gsap.fromTo(".box",
  { opacity: 0, scale: 0.5 }, // FROM
  { opacity: 1, scale: 1, duration: 1 } // TO
);
タイムライン:アニメーションのシーケンス化

タイムラインでは、複数のトゥイーンを順番に実行したり、重ねたりできます。

const tl = gsap.timeline();

// Sequential by default
tl.to(".box1", { x: 100, duration: 1 })
  .to(".box2", { y: 100, duration: 1 })
  .to(".box3", { rotation: 360, duration: 1 });

// With labels for organization
tl.addLabel("start")
  .to(".hero", { opacity: 1, duration: 1 })
  .addLabel("reveal")
  .to(".content", { y: 0, duration: 0.8 }, "reveal") // Start at "reveal" label
  .to(".cta", { scale: 1, duration: 0.5 }, "reveal+=0.5"); // 0.5s after "reveal"
位置パラメーター(タイムラインのタイミング)

タイムライン内でアニメーションを開始するタイミングを制御します。

const tl = gsap.timeline();

// Default: One after another
tl.to(".box1", { x: 100 })
  .to(".box2", { x: 100 }); // Starts after box1 finishes

// Start at the same time
tl.to(".box1", { x: 100 })
  .to(".box2", { y: 100 }, 0); // Starts at 0 seconds

// Relative positioning
tl.to(".box1", { x: 100, duration: 2 })
  .to(".box2", { y: 100 }, "-=1"); // Starts 1 second before box1 ends
  .to(".box3", { rotation: 360 }, "+=0.5"); // Starts 0.5s after box2 finishes

// At a specific time
tl.to(".box1", { x: 100 }, 2.5); // Starts at 2.5 seconds

ScrollTrigger の基本

基本的なスクロールアニメーション
gsap.registerPlugin(ScrollTrigger);

gsap.to(".box", {
  x: 500,
  scrollTrigger: {
    trigger: ".box",
    start: "top center", // When top of trigger hits center of viewport
    end: "bottom center",
    markers: true, // Development only - shows start/end positions
    scrub: true, // Links animation to scrollbar
    toggleActions: "play none none reverse" // onEnter onLeave onEnterBack onLeaveBack
  }
});
開始位置と終了位置

形式:"[trigger position] [viewport position]"

// Common patterns
start: "top top"      // Trigger top hits viewport top
start: "top center"   // Trigger top hits viewport center (default)
start: "top bottom"   // Trigger top hits viewport bottom
start: "center center" // Trigger center hits viewport center

// With offsets
start: "top top+=100"   // 100px below viewport top
start: "top 80%"        // 80% down the viewport
end: "+=500"            // 500px after start position
end: "bottom top"       // Trigger bottom hits viewport top
スクラブ(スクロールと同期するアニメーション)
// Boolean: Direct link to scrollbar (immediate)
scrub: true

// Number: Smoothing delay in seconds
scrub: 1  // Takes 1 second to "catch up" to scrollbar
scrub: 0.5 // Faster, tighter feel
トグルアクション

スクロール上の 4 つのポイントでアニメーションを制御します。

toggleActions: "play pause resume reset"
// onEnter | onLeave | onEnterBack | onLeaveBack

// Actions: play, pause, resume, restart, reset, complete, reverse, none

よく使われるパターン:

toggleActions: "play none none none"       // Play once on enter
toggleActions: "play none none reverse"    // Play forward, reverse back
toggleActions: "play complete reverse reset" // Full control
toggleActions: "restart pause resume pause"  // Restart on each enter

よく使われるパターン

1. スクロール時のフェードイン
gsap.from(".fade-in", {
  opacity: 0,
  y: 50,
  duration: 1,
  scrollTrigger: {
    trigger: ".fade-in",
    start: "top 80%",
    end: "top 50%",
    scrub: 1,
    once: true // Only animate once
  }
});
2. スクロール中に要素を固定
ScrollTrigger.create({
  trigger: ".panel",
  start: "top top",
  end: "+=500", // Pin for 500px of scrolling
  pin: true,
  pinSpacing: true // Add spacing (default true)
});
3. 水平スクロールセクション
const sections = gsap.utils.toArray(".panel");

gsap.to(sections, {
  xPercent: -100 * (sections.length - 1),
  ease: "none",
  scrollTrigger: {
    trigger: ".container",
    pin: true,
    scrub: 1,
    end: () => "+=" + document.querySelector(".container").offsetWidth
  }
});
4. 視差効果
// Slower movement (background layer)
gsap.to(".bg", {
  y: 200,
  ease: "none",
  scrollTrigger: {
    trigger: ".section",
    start: "top bottom",
    end: "bottom top",
    scrub: true
  }
});

// Faster movement (foreground layer)
gsap.to(".fg", {
  y: -100,
  ease: "none",
  scrollTrigger: {
    trigger: ".section",
    start: "top bottom",
    end: "bottom top",
    scrub: true
  }
});
5. スクロールでトリガーされるタイムライン
const tl = gsap.timeline({
  scrollTrigger: {
    trigger: ".container",
    start: "top top",
    end: "+=500",
    scrub: 1,
    pin: true,
    snap: {
      snapTo: "labels", // Snap to timeline labels
      duration: { min: 0.2, max: 3 },
      delay: 0.2,
      ease: "power1.inOut"
    }
  }
});

tl.addLabel("start")
  .from(".title", { scale: 0.3, rotation: 45, autoAlpha: 0 })
  .addLabel("color")
  .from(".box", { backgroundColor: "#28a92b" })
  .addLabel("spin")
  .to(".box", { rotation: 360 })
  .addLabel("end");
6. 複数の要素をまとめてアニメーション
// Loop through multiple elements
gsap.utils.toArray(".box").forEach((box, i) => {
  gsap.from(box, {
    y: 100,
    opacity: 0,
    scrollTrigger: {
      trigger: box,
      start: "top 80%",
      end: "top 50%",
      scrub: 1
    }
  });
});

// Or use ScrollTrigger.batch
ScrollTrigger.batch(".box", {
  onEnter: batch => gsap.to(batch, { opacity: 1, y: 0, stagger: 0.15 }),
  onLeave: batch => gsap.set(batch, { opacity: 0 }),
  start: "top 80%",
  once: true
});
7. 時差をつけたアニメーション
gsap.from(".item", {
  y: 50,
  opacity: 0,
  duration: 0.8,
  stagger: 0.1, // 0.1s between each item
  scrollTrigger: {
    trigger: ".grid",
    start: "top 80%"
  }
});

// Advanced stagger
gsap.from(".item", {
  scale: 0,
  duration: 1,
  stagger: {
    each: 0.1,
    from: "center", // "start", "center", "end", "edges", or index number
    grid: "auto", // For grid layouts
    ease: "power2.inOut"
  }
});

統合パターン

Three.js/WebGL との連携
import * as THREE from 'three';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

// Animate camera
gsap.to(camera.position, {
  x: 5,
  y: 3,
  z: 10,
  scrollTrigger: {
    trigger: "#section2",
    start: "top top",
    end: "bottom top",
    scrub: 1,
    onUpdate: () => camera.lookAt(scene.position)
  }
});

// Animate mesh rotation
gsap.to(mesh.rotation, {
  y: Math.PI * 2,
  scrollTrigger: {
    trigger: "#section3",
    start: "top bottom",
    end: "bottom top",
    scrub: true
  }
});

// Animate material properties
gsap.to(material, {
  opacity: 0,
  scrollTrigger: {
    trigger: "#section4",
    start: "top center",
    end: "center center",
    scrub: 1
  }
});
React との連携(useGSAP フック)
import { useRef } from 'react';
import { useGSAP } from '@gsap/react';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';

gsap.registerPlugin(ScrollTrigger);

function Component() {
  const container = useRef();
  const box = useRef();

  useGSAP(() => {
    gsap.to(box.current, {
      x: 200,
      scrollTrigger: {
        trigger: box.current,
        start: "top center",
        end: "bottom center",
        scrub: true,
        markers: true
      }
    });
  }, { scope: container }); // Scoping for cleanup

  return (
    <div ref={container}>
      <div ref={box} className="box">Animated Box</div>
    </div>
  );
}
React でのタイムライン共有
function App() {
  const [tl, setTl] = useState();

  useGSAP(() => {
    const timeline = gsap.timeline();
    setTl(timeline);
  }, []);

  return (
    <div>
      <Box timeline={tl} index={0} />
      <Circle timeline={tl} index={1} />
    </div>
  );
}

function Box({ timeline, index }) {
  const ref = useRef();

  useGSAP(() => {
    timeline && timeline.to(ref.current, { x: 100 }, index * 0.1);
  }, [timeline, index]);

  return <div ref={ref} className="box" />;
}
Locomotive Scroll との連携
import LocomotiveScroll from 'locomotive-scroll';

const scroller = new LocomotiveScroll({
  el: document.querySelector('[data-scroll-container]'),
  smooth: true
});

ScrollTrigger.scrollerProxy("[data-scroll-container]", {
  scrollTop(value) {
    return arguments.length ? scroller.scrollTo(value, 0, 0) : scroller.scroll.instance.scroll.y;
  },
  getBoundingClientRect() {
    return {top: 0, left: 0, width: window.innerWidth, height: window.innerHeight};
  },
  pinType: document.querySelector("[data-scroll-container]").style.transform ? "transform" : "fixed"
});

ScrollTrigger.addEventListener("refresh", () => scroller.update());
ScrollTrigger.refresh();

高度なテクニック

画像シーケンスのスクラブ
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");

const images = [];
const imageCount = 147;
const currentFrame = { value: 0 };

for (let i = 0; i < imageCount; i++) {
  const img = new Image();
  img.src = `./frames/frame_${i.toString().padStart(4, '0')}.jpg`;
  images.push(img);
}

images[0].onload = () => {
  canvas.width = images[0].width;
  canvas.height = images[0].height;
  render();
};

function render() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.drawImage(images[Math.floor(currentFrame.value)], 0, 0);
}

gsap.to(currentFrame, {
  value: imageCount - 1,
  snap: "value",
  ease: "none",
  scrollTrigger: {
    trigger: canvas,
    start: "top top",
    end: "+=500%",
    scrub: true,
    pin: true
  },
  onUpdate: render
});
要素までのスムーズなスクロール
gsap.registerPlugin(ScrollToPlugin);

// Scroll to element
gsap.to(window, {
  duration: 1,
  scrollTo: "#section2",
  ease: "power2.inOut"
});

// With offset
gsap.to(window, {
  duration: 1.5,
  scrollTo: { y: "#section2", offsetY: 50 },
  ease: "expo.inOut"
});

// Horizontal scroll
gsap.to(".container", {
  duration: 2,
  scrollTo: { x: 1000, autoKill: true }
});
条件付きアニメーション(メディアクエリー)
ScrollTrigger.matchMedia({
  // Desktop
  "(min-width: 800px)": function() {
    gsap.to(".box", {
      x: 500,
      scrollTrigger: {
        trigger: ".box",
        start: "top center",
        end: "bottom top",
        scrub: true
      }
    });
  },

  // Mobile
  "(max-width: 799px)": function() {
    gsap.to(".box", {
      y: 200,
      scrollTrigger: {
        trigger: ".box",
        start: "top 80%",
        scrub: 1
      }
    });
  }
});

パフォーマンスに関するベストプラクティス

1. will-change CSS を使用する
.animated-element {
  will-change: transform, opacity;
}
2. 再描画を最小限に抑える
// Good: Animate transform/opacity (GPU accelerated)
gsap.to(".box", { x: 100, opacity: 0.5 });

// Avoid: Animating layout properties
// gsap.to(".box", { width: 500, height: 300 }); // Causes reflow
3. ScrollTrigger を破棄する
// Kill individual trigger
const trigger = ScrollTrigger.create({ /* ... */ });
trigger.kill();

// Kill all triggers
ScrollTrigger.getAll().forEach(t => t.kill());

// In React with cleanup
useGSAP(() => {
  const tween = gsap.to(".box", { /* ... */ });

  return () => {
    tween.kill();
  };
}, []);
4. リサイズ処理をデバウンスする

ScrollTrigger はこれを自動で処理しますが、独自のリサイズ処理を実装する場合:

let resizeTimer;
window.addEventListener("resize", () => {
  clearTimeout(resizeTimer);
  resizeTimer = setTimeout(() => {
    ScrollTrigger.refresh();
  }, 250);
});
5. invalidateOnRefresh を使用する

リサイズ時に変化する動的な値の場合:

gsap.to(".box", {
  x: () => window.innerWidth / 2, // Dynamic value
  scrollTrigger: {
    trigger: ".box",
    start: "top center",
    invalidateOnRefresh: true // Recalculate x on resize
  }
});

よくある落とし穴

1. 同じ要素に複数のトゥイーンを適用する
// Problem: Second tween conflicts with first
gsap.to('h1', { x: 100, scrollTrigger: { /* ... */ } });
gsap.to('h1', { x: 200, scrollTrigger: { /* ... */ } }); // Jumps!

// Solution 1: Use fromTo
gsap.fromTo('h1', { x: 100 }, { x: 200, scrollTrigger: { /* ... */ } });

// Solution 2: Use immediateRender: false
gsap.to('h1', { x: 200, immediateRender: false, scrollTrigger: { /* ... */ } });

// Solution 3: Apply ScrollTrigger to timeline
const tl = gsap.timeline({ scrollTrigger: { /* ... */ } });
tl.to('h1', { x: 100 })
  .to('h1', { x: 200 });
2. 複数の要素に対してループを使用しない
// Wrong: Animates all at once
gsap.to('.section', {
  y: -100,
  scrollTrigger: { trigger: '.section', scrub: true }
});

// Right: Loop for individual triggers
gsap.utils.toArray('.section').forEach(section => {
  gsap.to(section, {
    y: -100,
    scrollTrigger: { trigger: section, scrub: true }
  });
});
3. プラグインの登録を忘れる
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { ScrollToPlugin } from 'gsap/ScrollToPlugin';

gsap.registerPlugin(ScrollTrigger, ScrollToPlugin); // Must register!
4. タイムライン内に ScrollTrigger をネストする
// Wrong: ScrollTriggers on individual tweens in timeline
const tl = gsap.timeline();
tl.to('.box1', { x: 100, scrollTrigger: { /* ... */ } }) // Don't do this!
  .to('.box2', { y: 100, scrollTrigger: { /* ... */ } });

// Right: ScrollTrigger on parent timeline
const tl = gsap.timeline({
  scrollTrigger: { /* ... */ }
});
tl.to('.box1', { x: 100 })
  .to('.box2', { y: 100 });

イージングのリファレンス

// Power easings (most common)
ease: "power1.out"  // Subtle deceleration
ease: "power2.inOut" // Smooth acceleration/deceleration
ease: "power3.in"   // Strong acceleration
ease: "power4.out"  // Very strong deceleration

// Special easings
ease: "elastic.out"  // Bouncy overshoot
ease: "back.out"     // Slight overshoot
ease: "bounce.out"   // Bouncing effect
ease: "circ.inOut"   // Circular motion feel
ease: "expo.inOut"   // Exponential (dramatic)

// Linear (for scrubbed scroll animations)
ease: "none"

ScrollTrigger のメソッド

// Refresh all ScrollTriggers (after DOM changes)
ScrollTrigger.refresh();

// Get all ScrollTriggers
const triggers = ScrollTrigger.getAll();

// Get specific trigger by ID
const st = ScrollTrigger.getById("myTrigger");

// Kill trigger
st.kill();

// Update trigger
st.scroll(500); // Programmatically set scroll position
st.enable();
st.disable();

// Global ScrollTrigger config
ScrollTrigger.config({
  limitCallbacks: true, // Improve performance
  syncInterval: 15 // Throttle scroll checks (ms)
});

// Debug mode
ScrollTrigger.defaults({
  markers: true // Show markers on all triggers
});

リソース

このスキルには、以下のリソースが含まれています。

references/
  • api_reference.md:API のクイックリファレンス(トゥイーンのメソッド、タイムラインのメソッド、ScrollTrigger のプロパティ)
  • easing_guide.md:用途別のビジュアルイージングリファレンス
  • common_patterns.md:よくあるシナリオですぐに使えるパターン
scripts/
  • generate_animation.py:GSAP コードのひな形を生成
  • timeline_builder.py:タイムラインのシーケンスを対話形式で作成
assets/
  • starter_scroll/:スクロール連動サイトの完全なテンプレート
  • easings/:イージングを視覚化する HTML ツール
  • examples/:実際の ScrollTrigger 使用例

このスキルを使用する場面

以下の場合にこのスキルを使用してください。

  • 滑らかなウェブアニメーションを作成する
  • スクロール連動型の体験を構築する
  • 視差効果を実装する
  • 複雑なアニメーションをシーケンス化する
  • DOM、SVG、Canvas、WebGL をアニメーション化する
  • Three.js または React とアニメーションを連携させる
  • スクロールテリングのウェブサイトを構築する
  • インタラクティブな UI トランジションを作成する

Three.js 固有のアニメーションについては、threejs-webgl スキルも参照してください。 アニメーションを組み込んだ React コンポーネントについては、motion-framer スキルを参照してください。

コメント