Communitygithub.com

SVG 動畫

當使用者要求「為 SVG 添加動畫」、「讓線條自行繪製」、「進行筆觸繪製 / 簽名動畫」、「將形狀變形為另一形狀」、「讓元素沿著路徑移動」、「為圖示/標誌添加動畫」或「為 SVG 漸層或濾鏡添加動畫」時使用。涵蓋透過 CSS、SMIL 和 GSAP 實現的筆觸偏移繪製、路徑變形、沿路徑運動以及動態圖示/漸層/濾鏡。

SVG 動畫 是什麼?

這項技能提供了一個全面的指南,用於建立清脆、輕量且可無限縮放的 SVG 向量動畫,非常適合圖示、插圖、標誌和數據標記。它針對不同的開發情境,提出了三種不同的動畫方法:CSS(用於簡單的宣告式動畫)、SMIL(直接在 SVG 內部使用 `<animate>` 元素,無需 JavaScript)以及 JS(使用 GSAP 或 Web Animations API 以獲得精確的控制和形狀變形)。該指南對於「筆觸繪製」動畫(例如,讓一條線條看起來像是自己畫出來的)提供了詳細的技術說明,包括如何使用 JavaScript 或 `pathLength` HTML 屬性來可靠地取得路徑長度。它還深入探討了更進階的主題,例如路徑變形(使用 GSAP 的 MorphSVG 或 Flubber 庫來處理點數不相符的形狀)、沿著自訂路徑的運動(使用 GSAP MotionPath 插件或較現代的 CSS `offset-path` 屬性)以及動態的 SVG 漸層和濾鏡效果。支援的平台包含所有現代瀏覽器,並提供了針對 React/Framer Motion 等框架的具體建議。此技能強調使用 SVGO 等工具進行最佳化、對 `prefers-reduced-motion` 的無障礙考量,以及一個清晰的交付工作流程,該流程會產生一個獨立的 HTML 檔案,並內建一個「搜尋工具」用以精確暫停動畫以進行截圖和驗證。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/nehakanjamala/personal_website/tree/HEAD/.agents/skills/svg-animation

在你喜歡的 AI 中提問

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

說明文件

SVG 動畫 是做什麼的?

清晰、輕量、可無限縮放的向量運動——非常適合圖示、插圖、標誌和數據標記。SVG 可以透過三種方式添加動畫:CSS(宣告式、簡單)、SMIL(在 SVG 內部使用 <animate>)和 JS(GSAP/Web Animations,用於控制和變形)。根據任務選擇;下面的技術說明了使用時機。

使用時機

  • 圖示、插圖、簽名、地圖的筆觸「繪製」動畫
  • 形狀/路徑變形和動態圖示狀態切換(選單 ↔ 關閉、播放 ↔ 暫停)
  • 讓元素沿著路徑移動(運動路徑)
  • 動態漸層、濾鏡(發光、位移)和動態標誌

核心技術

筆觸繪製( staple )

將虛線陣列設定為與路徑等長,將其完全偏移(不可見),然後將偏移量動畫化到 0。

.path {
  stroke-dasharray: var(--len);
  stroke-dashoffset: var(--len);
  animation: draw 1.4s ease forwards;
}
@keyframes draw { to { stroke-dashoffset: 0; } }

取得長度:

  • JS(最可靠):const len = path.getTotalLength(); path.style.setProperty("--len", len);
  • 無 JS 技巧:在 <path> 上設定 pathLength="1",然後 stroke-dasharray: 1; stroke-dashoffset: 1; 並動畫化到 0。這會將任何路徑標準化為 0-1 的長度,因此無需測量。

逆向(擦除)則是將偏移量從 0 動畫化回 len。使用 animation-delay 來交錯多個路徑。繪製方向遵循路徑的點順序;如果它「向後」繪製,請在編輯器中反轉路徑或將偏移符號取反。

將一個路徑變形為另一個

路徑會逐點進行插值,因此天真的變形需要兩個 d 屬性具有相同數量和類型的指令。兩種穩健的方法:

  • GSAP MorphSVG(自 GSAP 3.12 起免費)——自動處理不匹配的點數並找到良好的映射:
gsap.registerPlugin(MorphSVGPlugin);
gsap.to("#start", { morphSVG: "#end", duration: 0.8, ease: "power2.inOut" });
// 將任何形狀轉換為可變形的路徑:
MorphSVGPlugin.convertToPath("circle, rect, ellipse, line, polygon");
  • Flubber(小型獨立庫)——無需 GSAP 即可生成插值器,非常適合與 React/Framer Motion 一起使用:
import { interpolate } from "flubber";
const interpolator = interpolate(pathA, pathB, { maxSegmentLength: 2 });
// interpolator(0) === pathA, interpolator(1) === pathB; 將 t 輸入到一個補間動畫中。

對於手動編寫的變形(圖示切換),請保持兩個路徑具有相同的指令結構,並透過 Web Animations 或 CSS 直接動畫化 d(在現代瀏覽器中,d 可以透過 path("...") 進行動畫)。

沿著路徑運動

  • GSAP MotionPath(首選——控制、對齊、滾動觸發):
gsap.registerPlugin(MotionPathPlugin);
gsap.to("#rocket", {
  duration: 4, repeat: -1, ease: "none",
  motionPath: { path: "#track", align: "#track", autoRotate: true, alignOrigin: [0.5, 0.5] },
});

autoRotate: true 會使物件朝向路徑的切線方向;align 使座標相對於路徑元素。

  • SMIL(無需 JS):
<path id="track" d="M10,80 C40,10 120,10 150,80" fill="none"/>
<circle r="6" fill="#3b82f6">
  <animateMotion dur="3s" repeatCount="indefinite" rotate="auto">
    <mpath href="#track"/>
  </animateMotion>
</circle>
  • CSS offset-path(現代、宣告式):offset-path: path("M10,80 C..."); animation: move 3s linear infinite; 搭配 @keyframes move { to { offset-distance: 100%; } } 以及 offset-rotate: auto。

動態漸層和濾鏡

漸層:動畫化 gradientTransform 或停止偏移。一個光澤掃掠效果:

<linearGradient id="sheen">
  <stop offset="0%"  stop-color="#fff" stop-opacity="0"/>
  <stop offset="50%" stop-color="#fff" stop-opacity=".8"/>
  <stop offset="100%" stop-color="#fff" stop-opacity="0"/>
  <animateTransform attributeName="gradientTransform" type="translate"
    from="-1 0" to="1 0" dur="2s" repeatCount="indefinite"/>
</linearGradient>

濾鏡:動畫化 feDisplacementMap 的 scale 以產生黏稠/搖擺效果,feGaussianBlur 的 stdDeviation 以產生焦點拉移效果,或 feColorMatrix/feFlood 以產生發光效果。濾鏡很耗費繪圖資源——應謹慎使用,並儘可能優先使用 transform/opacity。

實作選擇(快速決定)

需求使用
單一宣告式繪製/淡入CSS
自包含,無 JS 套件SMIL(在 SVG 中使用 <animate*>)
協調、可拖曳、與滾動綁定GSAP
點數不相符的變形GSAP MorphSVG 或 Flubber
帶旋轉的沿路徑跟隨GSAP MotionPath / CSS offset-path

SMIL 注意事項:在 IE/舊版 Edge 中不受支援,並且歷史上曾被標記為棄用;為了最大覆蓋範圍或滾動同步,請優先使用 CSS 或 JS。對於常青瀏覽器中的自包含圖示資源,SMIL 仍然適用。

編寫與最佳化

  • 使用 SVGO 建置/清理:保留 viewBox,刪除編輯器元數據,但停用 cleanupIds/removeViewBox 以及任何會重新命名你從 CSS/JS/SMIL 中引用的 ID 的插件。如果你動畫化個別的子路徑或形狀,請停用 mergePaths 和 convertShapeToPath。
  • 將 SVG 內聯在 DOM 中(不要使用 <img src>),這樣 CSS/JS 才能存取其內部結構;<img> 嵌入的 SVG 只能透過內部的 SMIL/CSS 進行自我動畫。
  • 設定明確的 viewBox,避免固定的 width/height,以便資源能流暢縮放。
  • 對於繪製動畫,請確保路徑是實際的筆觸(fill:none; stroke:...),而不是填充的外框——dashoffset 只影響筆觸。
  • 尊重 prefers-reduced-motion:限制循環/大型運動;保留一個靜態的最終狀態。

交付與驗證(獨立 HTML)

打包的輔助腳本(scripts/):scripts/seek-shot.sh anim.html 0 1.5 3 會凍結 ?t=N 測試工具並對每個時刻進行截圖;scripts/contact-sheet.sh sheet.png frame-*.png 會將它們拼貼起來以便一覽審查。請參閱 scripts/README.md。

對於自包含的圖示/標誌/繪製動畫,交付物是一個可以直接在瀏覽器中開啟的 HTML 檔案——將 SVG 內聯在標記中,使用一種機制驅動動畫,無需建置步驟。對於向量資源來說,單一檔案是合適的層級;不要使用打包工具。

輸出合約:

  • 一個 .html 檔案:包含內聯 <svg>,以及 CSS @keyframes / 一個包含來自 CDN 的 GSAP 的 <script> / SMIL <animate*> —— 選擇一種驅動方式。
  • 包含與該驅動方式匹配的搜尋工具,以便可以凍結任何時刻進行截圖。

搜尋工具——凍結精確時刻。 ?t=N 會搜尋並暫停,以便截圖能夠捕捉到一個靜止畫面。使用與 SVG 動畫方式匹配的機制:

<script>
  const t = new URLSearchParams(location.search).get("t");
  if (t !== null) {
    const N = parseFloat(t);
    // SMIL:暫停 SVG 自身的時鐘並進行拖曳
    const svg = document.querySelector("svg");
    svg.pauseAnimations(); svg.setCurrentTime(N);
    // CSS @keyframes 繪製動畫:el.style.animationDelay=(-N)+"s"; el.style.animationPlayState="paused";
    // GSAP 時間軸:tl.pause(); tl.seek(N);
  }
  window.__ready = true;
</script>

驗證循環——渲染 → 凍結 → 截圖 → 檢查: 在開始/中間/結束時開啟檔案(?t=0、?t=<dur/2>、?t=<dur>),對每個進行截圖,並檢查保真度(筆觸繪製方向正確,變形端點乾淨)以及偽影(路徑被 viewBox 裁剪、因舊的 dashoffset 導致筆觸消失、FOUC、變形接縫處的卡頓)。任何無頭工具都可以:

npx playwright screenshot --wait-for-timeout=500 "file://$PWD/icon.html?t=0.7" frame-mid.png

在你完成之前:

  1. 可獨立開啟——無控制台錯誤,內聯 SVG 可存取,CDN(如果有)可載入。
  2. 你的驅動方式的搜尋機制能凍結一個確定的畫面格。
  3. 在開始/中間/結束時截圖——符合需求,沒有裁剪或超出 viewBox 的筆觸。
  4. 已尊重 prefers-reduced-motion——限制循環/大型運動,保留靜態最終狀態。
  5. 緩動效果是經過設計的——有意選擇了 ease/GSAP 緩動,沒有意外的 linear 繪製動畫。

參考檔案

  • references/svg-techniques.md——完整的 dashoffset 數學運算和 getTotalLength 陷阱、pathLength="1" 標準化、GSAP MorphSVG 與 Flubber 的決策指南及程式碼、一個圖示切換變形(漢堡選單↔關閉)、MotionPath/offset-path 細節、SMIL-vs-CSS-vs-JS 的權衡取捨,以及一個針對動畫調整的 SVGO 配置。

Individual skills in this repo

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

nehakanjamala/personal_website

This skill should be used when the user asks to "fix janky CSS animation", "make animation 60fps", "stop layout thrashing", "animate width/height/top/left smoothly", "convert animation to transform", "animate box-shadow performantly", "animate height auto", "FLIP animation", or "why is my scroll/hover animation choppy".

nehakanjamala/personal_website

This skill should be used when the user asks to "respect prefers-reduced-motion", "honor reduced motion", "make my animations accessible", "fix vestibular / motion-sickness issues", "add a useReducedMotion hook", "gate GSAP / Framer Motion / Lenis for reduced motion", or "meet WCAG 2.3.3 / C39". Provides tiered (not all-or-nothing) reduced-motion patterns in CSS and JS.

nehakanjamala/personal_website

Create, modify, debug, and deploy Apify Actors, and write their input and output schemas. Use when building an Actor from scratch, changing or troubleshooting Actor code, generating or updating .actor schema files, or pushing an Actor to the Apify platform. To wrap an existing non-Actor project, use apify-actorization instead.

nehakanjamala/personal_website

Convert existing projects into Apify Actors - serverless cloud programs. Actorize JavaScript/TypeScript (SDK with Actor.init/exit), Python (async context manager), or any language (CLI wrapper). Use when migrating code to Apify, wrapping CLI tools as Actors, or adding Actor SDK to existing projects.

nehakanjamala/personal_website

Deprecated. Output schema generation moved to the apify-actor-development skill; prefer that skill whenever it is available.

nehakanjamala/personal_website

Design and build an official Apify integration for a company's product - workflow-automation apps (Zapier/n8n-style), AI agent plugins (coding-agent skills+MCP bundles or OpenClaw/Hermes-style harnesses), AI framework packages (LangChain/LlamaIndex-style), or direct application clients via apify-client. Use when planning, creating, or reviewing an integration that exposes Apify Actors, runs, datasets, or key-value stores inside another product.

nehakanjamala/personal_website

Universal AI-powered web scraper for any platform. Scrape data from Instagram, Facebook, TikTok, YouTube, LinkedIn, X/Twitter, Google Maps, Google Search, Google Trends, Reddit, Airbnb, Yelp, and 15+ more platforms. Use for lead generation, brand monitoring, competitor analysis, influencer discovery, trend research, content analytics, audience analysis, review analysis, SEO intelligence, recruitment, or any data extraction task.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a glassmorphism effect", "frosted glass UI", "Apple liquid glass style", "frosted blur card", "translucent glass panel animation", "make a frosted nav bar", "build a glass modal/dialog", "animate a glass card on hover", or "add a refracting liquid-glass hero". Covers frosted translucent panels with backdrop-filter blur, edge/specular highlights, SVG liquid-glass refraction, motion on hover/scroll/enter, and accessible reduced-transparency fallbacks.

nehakanjamala/personal_website

This skill should be used when the user asks to "build a scroll animation", "add ScrollTrigger", "pin a section while scrolling", "scrub an animation to scroll", "create a hero timeline", "do a horizontal scroll section", "split text and animate words", "animate a layout change with GSAP Flip", "sync ScrollTrigger with Lenis", "Lenis smooth scroll jittery", "ScrollTrigger markers drift", "ScrollTrigger pins break with Lenis/Locomotive", or "set up smooth scroll with GSAP pinning". Covers GSAP timelines, ScrollTrigger, SplitText, Flip, and Lenis/Locomotive smooth-scroll sync for code-driven web motion.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a Lottie animation", "play a .lottie or .json animation", "integrate a Bodymovin/After Effects animation on web or mobile", "control Lottie playback / segments", "make a scroll-driven Lottie", "recolor a Lottie at runtime", or "export an AE animation to Lottie". Covers dotLottie/lottie-web integration, playback control, interactivity, theming, and the AE export checklist.

nehakanjamala/personal_website

This skill should be used when the user asks to "add a hover/press effect", "animate a toggle or switch", "build an animated like button", "make a toast/snackbar slide in", "animate a drawer or modal", "animate list reordering or add/remove", "do a shared-element layout transition", or "polish UI feedback". Covers UI motion with Framer Motion (motion/react) and modern CSS.

nehakanjamala/personal_website

This skill should be used when the user asks to "animate page or route transitions", "add a page transition or crossfade between views", "animate route changes in Next.js App Router", "use the View Transitions API", "AnimatePresence exit doesn't fire on navigation", or "Framer Motion exit animation not working / exit animation before unmount in Next.js". Covers enter/exit page-transition animation with the View Transitions API and Framer Motion, for Next.js App Router and general SPA routing.

nehakanjamala/personal_website

Scrape web pages using Scrapling with anti-bot bypass (like Cloudflare Turnstile), stealth headless browsing, spiders framework, adaptive scraping, and JavaScript rendering. Use when asked to scrape, crawl, or extract data from websites; web_fetch fails; the site has anti-bot protections; write Python code to scrape/crawl; or write spiders.

相關技能