Communitygithub.com

ComeOnOliver/skillshub

GSAP 動畫最佳實踐,涵蓋滾動觸發、性能優化、無障礙設計、響應式動畫與測試整合。適用於 WordPress 或任何網頁專案的動畫實作與審查。

skillshub 是什麼?

這項技能提供一套全面的 GSAP (GreenSock Animation Platform) 動畫最佳實踐指南,專為需要在網頁專案中實作專業、無障礙且高效能動畫的開發者設計。它涵蓋了從核心原則(如效能優先、無障礙設計與漸進增強)到進階動畫模式(例如淡入、交錯元素、視差效果、文字揭示與遮罩效果)的所有內容,並提供清晰的程式碼範例。此技能特別強調跨平台支援,包括 WordPress(提供 Enqueue 範例)、靜態網站及單頁應用程式 (SPA),同時深入探討如何透過 `prefers-reduced-motion` 媒體查詢確保無障礙體驗。此外,它整合了 `ScrollTrigger` 的最佳設定、響應式動畫的 `gsap.matchMedia()` 方法、效能最佳化技巧,以及與 Playwright 等測試工具的整合方法,協助開發者建立流暢且可靠的動畫體驗。

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

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

預覽

來自技能 README

skillshub 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 Enqueue

function theme_enqueue_gsap() {
    // GSAP 核心
    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. Hero 區域動畫時間軸

// 複雜的 Hero 區域序列
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 降級方案

/* 確保內容在沒有 JS 時可見 */
.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 Class 加到 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 屬性

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

// 不良 - 造成版面配置/繪製
gsap.to('.element', {
    left: 100,       // 觸發版面配置
    width: '200px',  // 觸發版面配置
    marginTop: 50    // 觸發版面配置
});

2. 批次處理相似動畫

// 對許多相似元素使用 batch
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 });

常見動畫函式庫

可複用的動畫 Class

// 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">第一行</div>
    <div class="line">第二行</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 的 Performance 標籤中檢查效能
  • 確認目標裝置上的 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

相關技能