描边绘制

DrawSVG

DrawSVG SVG 描边动画 线条绘制 路径绘制 Line Drawing Stroke Animation

逐步显示或隐藏 SVG 元素的描边,做出线条被「画出来」的效果;GSAP 的 DrawSVG 插件用百分比控制描边可见的区段。

又称:SVG 描边动画 · 线条绘制 · 路径绘制 · Line Drawing · Stroke Animation

  • GSAP
  • CSS
  • Claude / Cursor
drawSVG: '0%' → '100%' → '100% 100%'

Prompt 片段

  • Claude / Cursor
    用 GSAP DrawSVGPlugin 给页面里的签名 SVG 做绘制动画:所有 path 从 drawSVG: '0%' 画到 '100%',duration 1.6,ease power2.inOut,stagger 0.25。
  • Claude / Cursor'100% 100%' 表示可见区段收缩到终点
    做一个循环的线条动画:先把线画出来,停 0.8 秒后用 drawSVG: '100% 100%' 从起点方向擦除,放进 repeat: -1 的 timeline。
  • Claude / Cursor
    结合 ScrollTrigger,让流程图里的连接线随滚动逐步画出:scrub: true,ease: 'none',线条保持 fill: none 和 stroke-linecap: round。

是什么

描边绘制(DrawSVG)是让 SVG 的描边逐步出现或消失的动画。原理是利用 stroke-dasharraystroke-dashoffset:把描边设成一段与路径等长的虚线,再移动虚线的偏移量。手写这套逻辑需要先计算路径长度,DrawSVGPlugin 替你完成这一步,可用于 path、line、polyline、polygon、rect、circle、ellipse。它随 gsap 包免费提供,从 gsap/DrawSVGPlugin 导入。

drawSVG 的值描述描边可见的区段。上方演示中,曲线、直线和圆先从 '0%' 依次画到 '100%',停顿后再过渡到 '100% 100%',也就是可见区段的起点追上终点,线条从开头一侧被擦掉。

核心参数

写法 含义
drawSVG: '0%' 描边完全不可见
drawSVG: '100%' 描边完整显示,等同于 '0% 100%'
drawSVG: '20% 80%' 只显示 20% 到 80% 之间的一段
drawSVG: '100% 100%' 可见区段收缩到终点,常用于擦除
drawSVG: '50% 50%' 从中点开始,向两端展开或收拢

数值也可以写成绝对长度(不带 %),单位与 SVG 坐标一致。

代码示例

import { gsap } from 'gsap';
import { DrawSVGPlugin } from 'gsap/DrawSVGPlugin';

gsap.registerPlugin(DrawSVGPlugin);

// path、line、circle 等元素都需要有 stroke,fill 设为 none
const paths = document.querySelectorAll('svg .draw');

const tl = gsap.timeline({ repeat: -1, repeatDelay: 0.4 });
tl.fromTo(paths, { drawSVG: '0%' }, { drawSVG: '100%', duration: 1.6, ease: 'power2.inOut', stagger: 0.25 })
  .to(paths, { drawSVG: '100% 100%', duration: 0.9, ease: 'power2.in', stagger: 0.1 }, '+=0.8');

什么时候用

  • Logo、签名、手绘插画的开场绘制。
  • 流程图、路线图的连接线,配合滚动逐段画出。
  • 图表中的折线、进度环等需要「生长」效果的元素。

常见误区

  • 给没有描边的元素加动画:DrawSVG 只影响 stroke,图形必须设置 strokestroke-width,填充色不会被「画出来」。
  • 想绘制实心文字或图标:填充图形需要改用描边路径,或用遮罩配合描边来实现。
  • 元素缩放后线条粗细也变化:这是 SVG 本身的行为,与插件无关,可在设计阶段统一描边宽度。
esc