Frontend Lab
← 回到所有效果
G06V103gsap

SVG Path Draw

SVG 路徑繪製

難度 ★★★★★標籤 svg · path · strokeDashoffset2 min read

效果簡述

SVG 路徑像被「畫出來」一樣顯現。核心是 strokeDasharray + strokeDashoffset 動畫,這是純 SVG 技巧,GSAP 只是負責 tween。 連接線、簽名、流程圖最常用。

預設|drawSVG 0%→100%, 2s

Claude Code Prompt

💬 Claude Code Prompt
參考:V103 svg path draw
技術:SVG strokeDasharray + strokeDashoffset,用 gsap.to 補間

具體行為:
- pathRef.current.getTotalLength() 取得長度
- gsap.set(path, { strokeDasharray: len, strokeDashoffset: len })
- gsap.to(path, { strokeDashoffset: 0, duration: 2, ease: 'power2.inOut' })

限制:
- 必須是 stroke 的 path,fill-only 沒效果
- 太短的路徑(< 30px)看不出來
- 一頁多條時用 timeline 排序,別並發

完整程式碼

SvgPathDraw.tsx
'use client'

import gsap from 'gsap'
import { useEffect, useRef } from 'react'

export function SvgPathDraw() {
const path = useRef<SVGPathElement>(null)

useEffect(() => {
  if (!path.current) return
  const len = path.current.getTotalLength()
  gsap.set(path.current, { strokeDasharray: len, strokeDashoffset: len })
  gsap.to(path.current, {
    strokeDashoffset: 0,
    duration: 2,
    ease: 'power2.inOut',
  })
}, [])

return (
  <svg viewBox="0 0 200 120" fill="none" stroke="currentColor" strokeWidth="2">
    <path ref={path} d="M 20 60 Q 60 10, 100 60 T 180 60" />
  </svg>
)
}

何時用

  • ✅ Logo reveal
  • ✅ 流程圖 / 步驟連接線
  • ✅ 簽名 / 手寫感效果

何時別用

  • ❌ 純填色圖形(沒 stroke 就沒戲)
  • ❌ 複雜路徑 + 大量 path(效能差)
  • ❌ 期待精準時間控制的多 path 場景(用 timeline 排)

我踩過的坑

  1. 沒 set 初始 dashoffset 直接看見完整路徑:必須先 gsap.set 把 offset 設成 len,再 tween 到 0。

  2. getTotalLength() 在 SSR 拿不到:用 useEffect 確保 client 端 執行;或在 client mount 後計算。

  3. path 沒 stroke 看不見動畫:必須 stroke + fill: none。

相關效果

搜尋

按 ⌘K 隨時開啟