GSAP & ScrollTrigger 開発ガイド
概要
GSAP(GreenSock Animation Platform)は、高パフォーマンスでプロダクション品質のアニメーションを作成するための業界をリードするJavaScriptアニメーションライブラリです。ScrollTriggerは、スクロール駆動のアニメーションのためのGSAPの強力なプラグインです。これらを組み合わせることで、シンプルなUIトランジションから複雑なスクロールベースのストーリーテリング体験まで、あらゆるものを実現できます。
コアコンセプト
基本:トゥイーン(Tween)
トゥイーンとは、ポイントAからポイントBへの単一のアニメーションです。
// 状態TOへアニメーション(現在の状態から)
gsap.to(".box", {
x: 200,
rotation: 360,
duration: 1,
ease: "power2.inOut"
});
// 状態FROMからアニメーション(現在の状態へ)
gsap.from(".box", {
opacity: 0,
y: -50,
duration: 0.8
});
// FROM-TO(開始と終了の両方を定義)
gsap.fromTo(".box",
{ opacity: 0, scale: 0.5 }, // FROM
{ opacity: 1, scale: 1, duration: 1 } // TO
);
タイムライン:アニメーションの連続実行
タイムラインは、複数のトゥイーンを順番に、または重ねて調整します。
const tl = gsap.timeline();
// デフォルトでは順次実行
tl.to(".box1", { x: 100, duration: 1 })
.to(".box2", { y: 100, duration: 1 })
.to(".box3", { rotation: 360, duration: 1 });
// ラベルで整理
tl.addLabel("start")
.to(".hero", { opacity: 1, duration: 1 })
.addLabel("reveal")
.to(".content", { y: 0, duration: 0.8 }, "reveal") // "reveal"ラベルから開始
.to(".cta", { scale: 1, duration: 0.5 }, "reveal+=0.5"); // "reveal"の0.5秒後
位置パラメーター(タイムラインのタイミング)
タイムライン内でのアニメーションの開始タイミングを制御します:
const tl = gsap.timeline();
// デフォルト:次々に実行
tl.to(".box1", { x: 100 })
.to(".box2", { x: 100 }); // box1の終了後に開始
// 同じタイミングで開始
tl.to(".box1", { x: 100 })
.to(".box2", { y: 100 }, 0); // 0秒で開始
// 相対位置指定
tl.to(".box1", { x: 100, duration: 2 })
.to(".box2", { y: 100 }, "-=1"); // box1の終了1秒前に開始
.to(".box3", { rotation: 360 }, "+=0.5"); // box2の終了0.5秒後に開始
// 特定の時間に開始
tl.to(".box1", { x: 100 }, 2.5); // 2.5秒で開始
ScrollTriggerの基礎
基本的なスクロールアニメーション
gsap.registerPlugin(ScrollTrigger);
gsap.to(".box", {
x: 500,
scrollTrigger: {
trigger: ".box",
start: "top center", // トリガーの上部がビューポートの中央に来た時
end: "bottom center",
markers: true, // 開発時のみ - 開始/終了位置を表示
scrub: true, // アニメーションをスクロールバーに連動
toggleActions: "play none none reverse" // onEnter onLeave onEnterBack onLeaveBack
}
});
開始位置と終了位置
フォーマット:`"[トリガー位置] [ビューポート位置]"``
// よく使うパターン
start: "top top" // トリガーの上部がビューポートの上部にヒット
start: "top center" // トリガーの上部がビューポートの中央にヒット(デフォルト)
start: "top bottom" // トリガーの上部がビューポートの下部にヒット
start: "center center" // トリガーの中央がビューポートの中央にヒット
// オフセット付き
start: "top top+=100" // ビューポート上部から100px下
start: "top 80%" // ビューポートの80%の位置
end: "+=500" // 開始位置から500px後
end: "bottom top" // トリガーの下部がビューポートの上部にヒット
スクラブ(スクロール同期アニメーション)
// ブール値:スクロールバーに直接連動(即時)
scrub: true
// 数値:スムージングの遅延(秒)
scrub: 1 // スクロールバーに「追従」するのに1秒かかる
scrub: 0.5 // より速く、タイトな感覚
トグルアクション
4つのスクロールポイントでアニメーションを制御:
toggleActions: "play pause resume reset"
// onEnter | onLeave | onEnterBack | onLeaveBack
// アクション: play, pause, resume, restart, reset, complete, reverse, none
よく使うパターン:
toggleActions: "play none none none" // エンター時に一度だけ再生
toggleActions: "play none none reverse" // 順方向に再生、逆方向に戻る
toggleActions: "play complete reverse reset" // 完全制御
toggleActions: "restart pause resume pause" // エンターごとに再開
よく使うパターン
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 // 一度だけアニメーション
}
});
2. スクロール中の要素のピン留め
ScrollTrigger.create({
trigger: ".panel",
start: "top top",
end: "+=500", // 500pxのスクロールの間ピン留め
pin: true,
pinSpacing: true // スペーシングを追加(デフォルトは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. パララックス効果
// 遅い動き(背景レイヤー)
gsap.to(".bg", {
y: 200,
ease: "none",
scrollTrigger: {
trigger: ".section",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// 速い動き(前景レイヤー)
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", // タイムラインラベルにスナップ
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. バッチアニメーション(複数要素)
// 複数要素をループ処理
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
}
});
});
// または 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.1秒
scrollTrigger: {
trigger: ".grid",
start: "top 80%"
}
});
// 高度なスタガー
gsap.from(".item", {
scale: 0,
duration: 1,
stagger: {
each: 0.1,
from: "center", // "start", "center", "end", "edges", またはインデックス番号
grid: "auto", // グリッドレイアウト用
ease: "power2.inOut"
}
});
統合パターン
Three.js / WebGLとの統合
import * as THREE from 'three';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
// カメラのアニメーション
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)
}
});
// メッシュの回転アニメーション
gsap.to(mesh.rotation, {
y: Math.PI * 2,
scrollTrigger: {
trigger: "#section3",
start: "top bottom",
end: "bottom top",
scrub: true
}
});
// マテリアルプロパティのアニメーション
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 }); // スコープ設定によるクリーンアップ
return (
<div ref={container}>
<div ref={box} className="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);
// 要素にスクロール
gsap.to(window, {
duration: 1,
scrollTo: "#section2",
ease: "power2.inOut"
});
// オフセット付き
gsap.to(window, {
duration: 1.5,
scrollTo: { y: "#section2", offsetY: 50 },
ease: "expo.inOut"
});
// 横スクロール
gsap.to(".container", {
duration: 2,
scrollTo: { x: 1000, autoKill: true }
});
条件付きアニメーション(メディアクエリ)
ScrollTrigger.matchMedia({
// デスクトップ
"(min-width: 800px)": function() {
gsap.to(".box", {
x: 500,
scrollTrigger: {
trigger: ".box",
start: "top center",
end: "bottom top",
scrub: true
}
});
},
// モバイル
"(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. リペイントの制限
// 良い:transform/opacityをアニメーション(GPUアクセラレーション)
gsap.to(".box", { x: 100, opacity: 0.5 });
// 避ける:レイアウトプロパティのアニメーション
// gsap.to(".box", { width: 500, height: 300 }); // リフローを引き起こす
3. ScrollTriggerの破棄
// 個別のトリガーを削除
const trigger = ScrollTrigger.create({ /* ... */ });
trigger.kill();
// 全てのトリガーを削除
ScrollTrigger.getAll().forEach(t => t.kill());
// Reactでクリーンアップ
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, // 動的な値
scrollTrigger: {
trigger: ".box",
start: "top center",
invalidateOnRefresh: true // リサイズ時にxを再計算
}
});
よくある落とし穴
1. 同じ要素に対する複数のトゥイーン
// 問題:2番目のトゥイーンが1番目と競合する
gsap.to('h1', { x: 100, scrollTrigger: { /* ... */ } });
gsap.to('h1', { x: 200, scrollTrigger: { /* ... */ } }); // ジャンプする!
// 解決策1:fromToを使用
gsap.fromTo('h1', { x: 100 }, { x: 200, scrollTrigger: { /* ... */ } });
// 解決策2:immediateRender: falseを使用
gsap.to('h1', { x: 200, immediateRender: false, scrollTrigger: { /* ... */ } });
// 解決策3:タイムラインにScrollTriggerを適用
const tl = gsap.timeline({ scrollTrigger: { /* ... */ } });
tl.to('h1', { x: 100 })
.to('h1', { x: 200 });
2. 複数要素に対するループの未使用
// 間違い:一度にすべてをアニメーション
// gsap.to('.section', {
// y: -100,
// scrollTrigger: { trigger: '.section', scrub: true }
// });
// 正解:個別のトリガーにループ処理
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);
// 登録せずに使用しないでください!
4. レスポンシブ対応の不足
// 問題:固定値は小さな画面で壊れる
// gsap.to('.box', { x: 500, ... });
// 解決策:動的な値または関数を使用
gsap.to('.box', {
x: () => Math.min(window.innerWidth * 0.5, 500),
scrollTrigger: { trigger: '.box', invalidateOnRefresh: true }
});
// または matchMedia を使用
ScrollTrigger.matchMedia({
'(min-width: 768px)': () => { /* 大きな画面のアニメーション */ },
'(max-width: 767px)': () => { /* 小さな画面のアニメーション */ }
});