Communitygithub.com

高效能網頁動畫 - nehakanjamala/personal_website

用於修復卡頓的 CSS 動畫、將動畫提昇至 60fps、避免版面重排 (layout thrashing)、將寬/高/上/左的動畫轉換為 transform,並實現流暢的 box-shadow、height: auto 與 FLIP 動畫。

personal_website 是什麼?

這個技能專注於消除網頁動畫中因版面重排 (reflow) 或重繪 (repaint) 所導致的卡頓問題。瀏覽器渲染流程分為「佈局 → 繪製 → 合成」三個階段,唯有僅影響**合成**階段的屬性(`transform` 與 `opacity`)才能讓動畫在 60/120fps 維持流暢。此技能提供具體的替代方案,例如將 `width/height` 改為 `transform: scaleX()/scaleY()`,將 `top/left` 改為 `transform: translate()`,並透過偽元素的 `opacity` 模擬陰影動畫。技能也深入說明 FLIP 技巧,用來流暢地處理佈局變更(如元素重新排序或跨容器移動),以及現代化的 `height: auto` 動畫方法(`interpolate-size: allow-keywords` 與 CSS Grid 技巧)。此外,它詳細解釋如何避免「佈局重排風暴」(layout thrashing),教導開發者批次處理讀取與寫入操作。最後,這份文件還附帶完整的驗證流程,包含如何透過 DevTools Performance 面板確認動畫僅觸發合成階段,以及使用 Playwright 進行截圖與效能分析。

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

在你喜歡的 AI 中提問

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

說明文件

高效能網頁動畫

消除產生卡頓網頁動畫的第一大原因:動畫化那些會迫使瀏覽器在每一幀重新計算版面 (reflow) 或重繪 (repaint) 的屬性。瀏覽器按階段渲染 — 佈局 → 繪製 → 合成。對 width、height、top、left、margin、padding、box-shadow 或 filter 進行動畫化,會導致每一幀重新執行佈局和/或繪製,因而阻塞主執行緒。而對 transform 和 opacity 進行動畫化,則完全在合成器(通常是 GPU)上執行,跳過佈局與繪製,這正是讓動畫在 60/120fps 保持流暢的關鍵。

使用時機

當動畫出現卡頓或掉幀時、當滑鼠懸停/滾動效果感覺很重時、當對尺寸/位置/陰影進行動畫化時、當佈局變更需要平滑動畫(卡片重新排序、元素在容器間移動)時、當對 height: auto 進行動畫化時,或在審查動畫程式碼的效能時使用。

核心規則:僅對 transform 和 opacity 進行動畫化

將每個「昂貴的」動畫對應到一個便宜的替代方案。

動畫屬性(昂貴)觸發替代方式(便宜)
width / height佈局 + 繪製transform: scaleX()/scaleY() (+ 用 FLIP 實現真實尺寸)
top / left / margin佈局 + 繪製transform: translate()
box-shadow繪製透過偽元素的 opacity 對陰影進行動畫化
filter: blur()繪製(沉重)透過 opacity 交叉淡入淡出兩個圖層,或謹慎使用
background-position繪製對子圖層使用 transform: translate()
color / background繪製通常可接受;或交叉淡入淡出圖層

透過 transform 實現位置與尺寸

/* 不好:每一幀都動畫化佈局 */
.box { transition: left 300ms, width 300ms; left: 0; width: 100px; }
.box:hover { left: 200px; width: 200px; }

/* 好:僅合成器操作 */
.box {
  transition: transform 300ms ease;
  transform: translateX(0) scaleX(1);
  transform-origin: left center;
}
.box:hover { transform: translateX(200px) scaleX(2); }

scaleX 會扭曲內部內容(文字會被拉伸)。若要在不扭曲的情況下實現真正的縮放,請使用 FLIP。

透過偽元素 opacity 實現便宜的 box-shadow

每一幀對 box-shadow 進行動畫化,都會重新繪製一個大範圍的模糊區域。請改為在 ::after 上一次性地繪製陰影,然後僅對其 opacity 進行動畫化。

.card { position: relative; }
.card::after {
  content: "";
  position: absolute;
  inset: 0;
  border-radius: inherit;
  box-shadow: 0 12px 28px rgba(0,0,0,0.35);
  opacity: 0;
  transition: opacity 300ms ease;
  pointer-events: none;
}
.card:hover::after { opacity: 1; }

模糊的陰影被一次性地柵格化;懸浮時僅改變合成器的透明度 — 在任何幀率下都流暢。

FLIP:廉價地動畫化佈局變更

FLIP(First, Last, Invert, Play)僅使用 transform 來動畫化佈局變更(重新排序、調整大小、在容器間移動)。測量元素原本位置 (First) 和最終位置 (Last),施加一個反向變換使其視覺上保持不動,然後將變換動畫化回原始狀態 (Play)。DOM 最終位於其實際的最終佈局;運動則完全是合成器的工作。

function flip(el, mutate) {
  const first = el.getBoundingClientRect();   // First
  mutate();                                    // 變更 DOM/佈局
  const last = el.getBoundingClientRect();     // Last

  const dx = first.left - last.left;
  const dy = first.top - last.top;
  const sx = first.width  / last.width;
  const sy = first.height / last.height;

  el.animate(
    [
      { transformOrigin: 'top left',
        transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})` }, // Invert
      { transformOrigin: 'top left', transform: 'none' },               // Play
    ],
    { duration: 300, easing: 'cubic-bezier(0.2, 0, 0, 1)' }
  );
}

// 用法:將一個元素動畫化到新的網格位置
flip(card, () => targetContainer.appendChild(card));

Web Animations API 的 animate() 方法會在合成器上執行變換。對於多個元素,請在任何變動之前批次讀取所有 getBoundingClientRect()(請參閱下方的佈局重排風暴)。

對 height: auto 進行動畫化

height: auto 在傳統上不可進行插值。現代與備用方案:

/* 現代寫法(Chrome 129+/支援的瀏覽器):啟用關鍵字尺寸的動畫 */
.panel {
  interpolate-size: allow-keywords;   /* 啟用對 auto 的來回動畫 */
  height: 0;
  overflow: clip;
  transition: height 300ms ease;
}
.panel.open { height: auto; }
/* calc-size() 也可運作:height: calc-size(auto, size); */
/* 現今穩健的備用方案:CSS 網格 1fr -> 0fr */
.wrapper {
  display: grid;
  grid-template-rows: 0fr;            /* 摺疊 */
  transition: grid-template-rows 300ms ease;
}
.wrapper.open { grid-template-rows: 1fr; }
.wrapper > .content { overflow: hidden; min-height: 0; }

網格技巧動畫化軌道尺寸(對合成器友善且廣泛支援),且不需要 JS 測量高度。在目標瀏覽器支援時使用 interpolate-size: allow-keywords / calc-size(auto, size);保留網格技術作為跨瀏覽器的預設方案。

避免佈局重排風暴(批次讀取,再批次寫入)

在寫入之後讀取一個佈局屬性(offsetWidth、getBoundingClientRect、scrollTop、getComputedStyle)會強制進行同步回流。在迴圈中交錯進行讀寫(「佈局重排風暴」)可能會在每一幀中觸發數十次強制回流。

// 不好:讀、寫、讀、寫... 每次迭代都強制回流
items.forEach((el) => {
  const w = el.offsetWidth;          // 讀取(強制佈局)
  el.style.width = w * 1.5 + 'px';   // 寫入(使佈局失效)
});

// 好:批次讀取所有值,再批次寫入所有值
const widths = items.map((el) => el.offsetWidth);  // 所有讀取
items.forEach((el, i) => {                          // 所有寫入
  el.style.width = widths[i] * 1.5 + 'px';
});

對於需要與影格同步的工作,請在 requestAnimationFrame 回呼中讀取並套用寫入;像 fastdom 這樣的函式庫將這種讀/寫排程形式化。

will-change:謹慎使用

will-change: transform 會提前將一個元素提升到自己的合成器圖層,避免在動畫開始時發生卡頓。但每個被提升的圖層都會消耗 GPU 記憶體,過度使用反而會降低效能。

.menu { will-change: transform; }   /* 僅對即將動畫化的元素使用 */

規則:僅在動畫即將開始前套用(例如在 hover/父元素狀態下),在閒置時移除它(設為 will-change: auto)。永遠不要大量套用於許多元素,也不要永久將其留在大型/數量眾多的節點上。單一的 transform: translateZ(0) hack 也能達到同樣的提升效果,但更難取消 — 推薦使用 will-change。

交付與驗證(獨立 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 檔案,可直接在瀏覽器中開啟 — 標記、CSS/JS 動畫以及一個凍結測試框架都在同一個檔案中。對於這個技能,驗證是雙重的:畫面必須看起來正確,並且產生成本要低(僅合成器)。

輸出規範:

  • 一個 .html 檔案,若有依賴則透過 CDN 引入;動畫由 CSS transitions/@keyframes 或 Web Animations API 驅動。
  • 一個凍結機制,讓截圖能夠落在一個確定的影格上:
    • CSS @keyframes → ?t=N 設定 el.style.animationDelay = (-N)+'s'; el.style.animationPlayState = 'paused'。
    • WAAPI / JS → 保留動畫物件並執行 anim.pause(); anim.currentTime = N*1000。

驗證循環 — 凍結 → 截圖,然後進行卡頓分析:

  1. 在無頭模式下於開始 / 中間 / 結束 (?t=0、中間、結束) 開啟,分別截圖;確認運動在視覺上是正確的(沒有因 scaleX 而產生的剪裁或拉伸文字、FLIP 落在真實佈局上、陰影/高度轉場看起來正確)。
  2. 確認它是僅合成器操作 — 這是這個技能的核心目標。可以:
    • DevTools → Performance:錄製動畫,檢查每幀中是否沒有紫色的「Layout」或綠色的「Paint」條(僅有「Composite Layers」)。
    • 或者無頭追蹤:使用 npx playwright screenshot 進行視覺截圖,再加上 CDP/tracing 捕獲,並斷言在動畫期間沒有觸發 Layout/Paint 事件。
  3. 觀察 FPS/「Frame Rendering Stats」疊加層保持在 60 — 掉幀意味著有昂貴的屬性被重新引入。
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/anim.html?t=0.3" frame.png

完成之前:

  1. 可獨立開啟 — 無控制台錯誤。
  2. 每幀僅 transform / opacity 進行動畫化;DevTools 顯示沒有每幀的 Layout/Paint。
  3. 在開始 / 中間 / 結束時截圖 — 正確,沒有 scaleX 的文字扭曲,FLIP 準確落在最終位置。
  4. 保持 60fps;will-change 即時套用並在閒置時移除(沒有殘留的圖層)。
  5. 遵守 prefers-reduced-motion。

快速參考

目標這樣做
移動元素transform: translate()
不扭曲地調整大小使用 transform 的 FLIP
懸浮時的陰影對陰影偽元素的 opacity 進行動畫化
展開至內容高度Grid 0fr→1fr,或 interpolate-size: allow-keywords
多個元素移動批次讀取 getBoundingClientRect,再批次寫入
平滑的動畫啟動即時使用 will-change,閒置時移除
確認是僅合成器操作DevTools Performance:每幀無紫色「Layout」/綠色「Paint」

注意事項

  • scaleX/scaleY 會拉伸文字和子元素;當內容必須保持清晰時,請使用 FLIP。
  • transform 的百分比是相對於元素自身的盒子,而不是父元素 — 這與 left: % 不同。
  • 過度使用 will-change 或 translateZ(0) 會建立過多圖層,反而損害效能;僅提升要動畫化的元素。
  • filter 和 backdrop-filter 與合成器有關,但仍然昂貴;應透過 opacity 交叉淡入淡出來動畫化它們的存在,而不是對模糊半徑進行動畫化。
  • Grid 1fr→0fr 的內容必須設定 overflow: hidden 和 min-height: 0,否則它不會摺疊。
  • 永遠要將非必要的動畫置於 @media (prefers-reduced-motion: reduce) 的保護下。

參考檔案

  • references/patterns-and-profiling.md — 完整的可執行範例(手風琴、清單重新排序、視差滾動),DevTools 效能分析逐步指南以確認僅合成器幀,以及減少動作模式的範例和一個屬性成本速查表。

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 "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.

nehakanjamala/personal_website

This skill should be used when the user asks to "animate an SVG", "make a line draw itself on", "do a stroke draw-on / signature animation", "morph one shape into another", "move an element along a path", "animate an icon/logo", or "animate an SVG gradient or filter". Covers stroke-dashoffset draw-on, path morphing, motion-along-path, and animated icons/gradients/filters via CSS, SMIL, and GSAP.

相關技能