Communitygithub.com

GSAPアニメーションのベストプラクティス

Webデザイン向けGSAPアニメーションのベストプラクティス - スクロールトリガー、パフォーマンス最適化、アクセシビリティ、レスポンシブアニメーション、テスト統合を含む。WordPressやWebプロジェクトでアニメーションを実装・レビューする際に使用。

GSAPアニメーションのベストプラクティス とは?

このスキルは、GSAP (GreenSock Animation Platform) を使用したプロフェッショナルでアクセシブルかつ高性能なアニメーションを実装するための包括的なガイドです。パフォーマンス最適化(transformとopacityのGPU高速化)、アクセシビリティ(prefers-reduced-motionの尊重、コンテンツの可視性確保)、プログレッシブエンハンスメント(アニメーションなしでも動作)の3つの核心理念に基づいています。GSAPとScrollTriggerの基本的なセットアップ方法(CDN/WordPressエンキュー)から、スクロールに応じたフェードイン、パララックス、テキストリビール、カーテンリビール、ヒーローアニメーションタイムラインなどの具体的なアニメーションパターンまでをカバーします。さらに、MatchMedia を用いたレスポンシブアニメーション、パフォーマンス最適化テクニック(バッチ処理、未使用トリガーのクリーンアップ、遅延初期化)、ScrollTriggerのベストプラクティス、テスト統合(VisualQA、Playwright)、再利用可能なアニメーションライブラリの構築、デバッグ方法、配信前チェックリストも含まれており、あらゆるWebプロジェクト(特にWordPress)で活用できます。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/aiskillstore/marketplace/crazyswami/gsap-animations

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

プレビュー

スキル README より

GSAPアニメーションのベストプラクティス preview

ドキュメント

GSAPアニメーションのベストプラクティス は何をしますか?

GSAP (GreenSock Animation Platform) を使用したプロフェッショナルでアクセシブルかつ高性能なアニメーションを実装するための包括的なガイドです。

核心理念

1. パフォーマンス最優先

  • transform と opacity のみをアニメーションさせる(GPU高速化)
  • width、height、top、left、margin、padding のアニメーションは避ける
  • will-change は控えめに使用する
  • すべてのデバイスで60fpsを目標にする

2. アクセシビリティを常に考慮

  • prefers-reduced-motion を尊重する
  • JavaScriptがなくてもコンテンツが表示されるようにする
  • 重要なコンテンツをアニメーションの背後に隠さない
  • 長時間のアニメーションにはスキップ/一時停止のコントロールを提供する

3. プログレッシブエンハンスメント

  • アニメーションがなくてもコンテンツが動作する必要がある
  • アニメーションは機能性を強化するものであり、置き換えるものではない
  • アニメーションを無効にした状態でテストする

GSAPのセットアップ

インストール

<!-- CDN(WordPressに推奨) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js"></script>

<!-- オプションプラグイン -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollSmoother.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/SplitText.min.js"></script>

WordPressでのエンキュー

function theme_enqueue_gsap() {
    // GSAP Core
    wp_enqueue_script(
        'gsap',
        'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js',
        array(),
        '3.12.5',
        true
    );

    // ScrollTrigger
    wp_enqueue_script(
        'gsap-scrolltrigger',
        'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/ScrollTrigger.min.js',
        array('gsap'),
        '3.12.5',
        true
    );

    // テーマのアニメーション
    wp_enqueue_script(
        'theme-animations',
        get_theme_file_uri('/assets/js/animations.js'),
        array('gsap', 'gsap-scrolltrigger'),
        filemtime(get_theme_file_path('/assets/js/animations.js')),
        true
    );
}
add_action('wp_enqueue_scripts', 'theme_enqueue_gsap');

アニメーションパターン

1. スクロールに応じたフェードイン

// 基本的なフェードイン
gsap.from('.fade-in', {
    opacity: 0,
    y: 50,
    duration: 1,
    stagger: 0.2,
    scrollTrigger: {
        trigger: '.fade-in',
        start: 'top 80%',
        toggleActions: 'play none none none'
    }
});

2. 要素の段階的表示

// カードが一つずつ出現
gsap.from('.card', {
    opacity: 0,
    y: 100,
    duration: 0.8,
    stagger: {
        amount: 0.6,
        from: 'start'
    },
    ease: 'power2.out',
    scrollTrigger: {
        trigger: '.cards-container',
        start: 'top 75%'
    }
});

3. パララックス効果

// 画像の微妙なパララックス
gsap.to('.parallax-image', {
    yPercent: -20,
    ease: 'none',
    scrollTrigger: {
        trigger: '.parallax-section',
        start: 'top bottom',
        end: 'bottom top',
        scrub: true
    }
});

4. テキストの一行ずつの表示

// SplitTextプラグインが必要(Club GreenSock)
// または以下のCSSベースの代替手段を使用

// CSS代替手段 - 各行をspanでラップ
gsap.from('.reveal-line', {
    opacity: 0,
    y: '100%',
    duration: 0.8,
    stagger: 0.1,
    ease: 'power3.out',
    scrollTrigger: {
        trigger: '.text-reveal',
        start: 'top 80%'
    }
});

5. カーテン/マスクリビール

// スライドするマスクで画像を表示
gsap.to('.curtain-mask', {
    scaleX: 0,
    transformOrigin: 'right center',
    duration: 1.2,
    ease: 'power4.inOut',
    scrollTrigger: {
        trigger: '.curtain-container',
        start: 'top 70%'
    }
});

6. ヒーローアニメーションのタイムライン

// 複雑なヒーローシーケンス
const heroTL = gsap.timeline({
    defaults: { ease: 'power3.out' }
});

heroTL
    .from('.hero-bg', { scale: 1.2, duration: 1.5 })
    .from('.hero-title', { opacity: 0, y: 100, duration: 1 }, '-=1')
    .from('.hero-subtitle', { opacity: 0, y: 50, duration: 0.8 }, '-=0.5')
    .from('.hero-cta', { opacity: 0, y: 30, duration: 0.6 }, '-=0.3');

アクセシビリティ

動きの抑制への対応

// ユーザーの設定を確認
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

// 方法1: すべてのアニメーションを無効にする
if (prefersReducedMotion) {
    gsap.globalTimeline.timeScale(0);
    ScrollTrigger.getAll().forEach(st => st.kill());
}

// 方法2: 簡略化されたアニメーション
const animationConfig = prefersReducedMotion
    ? { duration: 0, stagger: 0 }
    : { duration: 1, stagger: 0.2 };

gsap.from('.element', {
    opacity: 0,
    y: prefersReducedMotion ? 0 : 50,
    ...animationConfig
});

CSSフォールバック

/* JavaScriptなしでもコンテンツが表示されるようにする */
.fade-in {
    opacity: 1;
    transform: translateY(0);
}

/* アニメーションが実行される場合のみ非表示にする */
.js .fade-in {
    opacity: 0;
    transform: translateY(50px);
}

/* CSSでも動きの抑制設定を尊重する */
@media (prefers-reduced-motion: reduce) {
    .js .fade-in {
        opacity: 1;
        transform: none;
    }
}

JSクラスをHTMLに追加

// スクリプトの先頭で追加
document.documentElement.classList.add('js');

レスポンシブアニメーション

ブレークポイントを考慮したアニメーション

// レスポンシブアニメーションを作成
const mm = gsap.matchMedia();

mm.add('(min-width: 1024px)', () => {
    // デスクトップ用アニメーション
    gsap.from('.hero-image', {
        x: 100,
        opacity: 0,
        duration: 1.2
    });

    return () => {
        // ブレークポイント変更時のクリーンアップ
    };
});

mm.add('(max-width: 1023px)', () => {
    // モバイル用アニメーション(よりシンプルに)
    gsap.from('.hero-image', {
        opacity: 0,
        duration: 0.8
    });
});

リサイズ時にリフレッシュ

// リサイズ時にScrollTriggerを再計算
let resizeTimer;
window.addEventListener('resize', () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(() => {
        ScrollTrigger.refresh();
    }, 250);
});

パフォーマンス最適化

1. Transformプロパティのみを使用

// GOOD - GPU高速化
// x: 100          // transform: translateX
// y: 50           // transform: translateY
// rotation: 45    // transform: rotate
// scale: 1.2      // transform: scale
// opacity: 0.5
gsap.to('.element', {
    x: 100,
    y: 50,
    rotation: 45,
    scale: 1.2,
    opacity: 0.5
});

// BAD - レイアウト/ペイントを引き起こす
// left: 100       // レイアウトをトリガー
// width: '200px'  // レイアウトをトリガー
// marginTop: 50   // レイアウトをトリガー
gsap.to('.element', {
    left: 100,
    width: '200px',
    marginTop: 50
});

2. 似たようなアニメーションのバッチ処理

// 多くの似た要素にはバッチを使用
ScrollTrigger.batch('.card', {
    onEnter: batch => gsap.to(batch, {
        opacity: 1,
        y: 0,
        stagger: 0.1
    }),
    start: 'top 85%'
});

3. 未使用のScrollTriggerを削除

// SPAでのナビゲーションやコンポーネントのアンマウント時にクリーンアップ
function cleanup() {
    ScrollTrigger.getAll().forEach(st => st.kill());
    gsap.killTweensOf('*');
}

4. 遅延初期化

// 表示されているセクションのアニメーションのみを初期化
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            initSectionAnimations(entry.target);
            observer.unobserve(entry.target);
        }
    });
}, { rootMargin: '100px' });

document.querySelectorAll('.animated-section').forEach(section => {
    observer.observe(section);
});

ScrollTriggerのベストプラクティス

1. 適切な開始/終了ポイント

// よくある間違いを避ける
ScrollTrigger.create({
    trigger: '.section',
    start: 'top 80%',    // トリガーの上端がビューポートの上から80%の位置に来たとき
    end: 'bottom 20%',   // トリガーの下端がビューポートの上から20%の位置に来たとき
    markers: true,       // デバッグのみ!本番環境では削除すること!
});

2. ピンセクションを慎重に扱う

// ピン留めはレイアウト問題を引き起こす可能性がある
ScrollTrigger.create({
    trigger: '.pinned-section',
    start: 'top top',
    end: '+=100%',
    pin: true,
    pinSpacing: true,    // 通常はtrueにする
    anticipatePin: 1     // モバイルで役立つ
});

3. 画像の読み込みを扱う

// 位置を計算する前に画像の読み込みを待つ
ScrollTrigger.config({
    ignoreMobileResize: true
});

window.addEventListener('load', () => {
    ScrollTrigger.refresh();
});

// または、遅延読み込み画像の後にリフレッシュ
document.querySelectorAll('img[loading="lazy"]').forEach(img => {
    img.addEventListener('load', () => ScrollTrigger.refresh());
});

テスト統合

Visual QAとの互換性

visual-qaスキルがアニメーションを正しくキャプチャするために:

// すべてのアニメーションを即座に完了させる関数を公開
window.completeAllAnimations = function() {
    gsap.globalTimeline.progress(1);
    ScrollTrigger.getAll().forEach(st => {
        st.scroll(st.end);
    });
};

// または、スクリーンショット用にアニメーションを完全にスキップする
if (window.location.search.includes('skip-animations')) {
    gsap.globalTimeline.timeScale(100);
}

Playwrightでのテスト

// Playwrightテスト内
await page.evaluate(() => {
    if (window.completeAllAnimations) {
        window.completeAllAnimations();
    }
});
await page.waitForTimeout(500);
await page.screenshot({ path: 'screenshot.png', fullPage: true });

共通アニメーションライブラリ

再利用可能なアニメーションクラス

// animations.js - 再利用可能なアニメーションライブラリ

const Animations = {
    // すべてのアニメーションを初期化
    init() {
        if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
            return;
        }

        this.fadeIn();
        this.slideIn();
        this.parallax();
        this.textReveal();
    },

    fadeIn() {
        gsap.utils.toArray('[data-animate="fade-in"]').forEach(el => {
            gsap.from(el, {
                opacity: 0,
                y: 50,
                duration: 0.8,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 85%',
                    once: true
                }
            });
        });
    },

    slideIn() {
        gsap.utils.toArray('[data-animate="slide-left"]').forEach(el => {
            gsap.from(el, {
                opacity: 0,
                x: -100,
                duration: 1,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 80%',
                    once: true
                }
            });
        });

        gsap.utils.toArray('[data-animate="slide-right"]').forEach(el => {
            gsap.from(el, {
                opacity: 0,
                x: 100,
                duration: 1,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 80%',
                    once: true
                }
            });
        });
    },

    parallax() {
        gsap.utils.toArray('[data-parallax]').forEach(el => {
            const speed = el.dataset.parallax || 0.2;
            gsap.to(el, {
                yPercent: -100 * speed,
                ease: 'none',
                scrollTrigger: {
                    trigger: el.parentElement,
                    start: 'top bottom',
                    end: 'bottom top',
                    scrub: true
                }
            });
        });
    },

    textReveal() {
        gsap.utils.toArray('[data-animate="text-reveal"]').forEach(el => {
            const lines = el.querySelectorAll('.line');
            gsap.from(lines, {
                opacity: 0,
                y: '100%',
                duration: 0.8,
                stagger: 0.1,
                scrollTrigger: {
                    trigger: el,
                    start: 'top 80%',
                    once: true
                }
            });
        });
    },

    // 動的コンテンツ後にリフレッシュ
    refresh() {
        ScrollTrigger.refresh();
    },

    // SPAナビゲーション用のクリーンアップ
    destroy() {
        ScrollTrigger.getAll().forEach(st => st.kill());
        gsap.killTweensOf('*');
    }
};

// DOM準備完了時に初期化
document.addEventListener('DOMContentLoaded', () => Animations.init());

HTMLでの使用例

<!-- フェードイン -->
<div data-animate="fade-in">コンテンツ</div>

<!-- 左からスライド -->
<div data-animate="slide-left">コンテンツ</div>

<!-- パララックス (0.2 = 20%の速度) -->
<img data-parallax="0.3" src="image.jpg">

<!-- テキストリビール(行のラッピングが必要) -->
<div data-animate="text-reveal">
    <div class="line">1行目</div>
    <div class="line">2行目</div>
</div>

デバッグ

マーカーの有効化

ScrollTrigger.defaults({
    markers: true  // 開始/終了マーカーを表示
});

アニメーションイベントのログ

gsap.to('.element', {
    x: 100,
    onStart: () => console.log('アニメーション開始'),
    onComplete: () => console.log('アニメーション完了'),
    onUpdate: self => console.log('進捗:', self.progress())
});

問題の確認

// すべてのScrollTriggerをリスト表示
console.log('ScrollTriggers:', ScrollTrigger.getAll());

// 要素が存在するか確認
const el = document.querySelector('.animated-element');
if (!el) console.warn('アニメーションターゲットが見つかりません!');

チェックリスト

ローンチ前

  • すべての markers: true を削除
  • prefers-reduced-motion: reduce でテスト
  • 実機モバイルデバイスでテスト(DevToolsだけでなく)
  • DevToolsのパフォーマンスタブでパフォーマンスを確認
  • ターゲットデバイスで60fpsを確認
  • JavaScriptなしでもコンテンツが表示されること
  • ScrollTriggerリフレッシュ前に画像が遅延読み込みされていること
  • レイアウトスラッシングがないこと(レイアウトプロパティのアニメーションを避ける)

Visual QA統合

  • スクリーンショット前にアニメーションが完了していること
  • ページ全体のスクロールで全てのアニメーションがトリガーされること
  • スクリーンショットが最終的なアニメーション状態をキャプチャしていること
  • すべてのビューポートサイズでテスト

リソース

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices.

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

関連スキル