教程 animejs tutorial

SVG 路径绘制动画

使用 strokeDasharray 和 strokeDashoffset,我们可以模拟出“线条被逐步绘制”的动态视觉效果,常用于:

  • 手绘风格动画
  • Logo 绘制过渡
  • 图表加载动画

动画原理说明

SVG 路径元素 <path> 默认是连续曲线或直线段。通过:

  • stroke-dasharray: 定义虚线间隔(可以设为路径总长)
  • stroke-dashoffset: 设置绘制的起点偏移量

配合 Anime.js 的动画控制,即可实现路径“从无到有”地绘制出来。

动画示例代码

js
anime({
  targets: "#path",
  strokeDashoffset: [anime.setDashoffset, 0],
  easing: "easeInOutSine",
  duration: 2000,
});

小结

通过 Anime.js 操作 SVG 路径动画,可以实现高质量、无失真的矢量绘制动效。

示例演示

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>SVG 路径绘制动画</title> <style> body { background: #f8f8f8; font-family: sans-serif; text-align: center; padding-top: 60px; }

svg {
  width: 240px;
  height: 240px;
  margin: 0 auto;
}

path {
  fill: none;
  stroke: #F67280;
  stroke-width: 3;
  stroke-linecap: round;
}

#startBtn {
  margin-top: 20px;
  padding: 8px 16px;
  background-color: #4FC08D;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
}

#startBtn:hover {
  background-color: #3a9d6f;
}

</style> </head>

<body> <svg viewBox="0 0 100 100"> <path id="path" d="M10 80 C 40 10, 65 10, 90 80" /> </svg>

<button id="startBtn">点击绘制路径</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js&quot;&gt;&lt;/script&gt; <script> document.getElementById(‘startBtn’).onclick = function () { anime({ targets: ‘#path’, strokeDashoffset: [anime.setDashoffset, 0], easing: ‘easeInOutSine’, duration: 2000 }); }; </script> </body>

</html>

✅ 效果:点击按钮后,一条平滑曲线被“绘制”出来,形成流畅自然的路径动画,常用于品牌 LOGO 展示或 SVG 图形绘制演示。