教程 animejs tutorial

SVG 动画技巧

Anime.js 支持对 SVG 元素进行高效动画处理,尤其适合线条、图标、路径等动画场景,常用于 LOGO 绘制、进度图等。

支持的 SVG 动画属性

你可以使用 Anime.js 操作 SVG 的以下属性:

  • stroke, fill
  • strokeDasharray, strokeDashoffset
  • transform: translate, rotate, scale, skew
  • 路径动画(如 <path d="">)

常见技巧:线条绘制动画

使用 strokeDashoffset 可实现「线条逐步绘制」的视觉效果:

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

anime.setDashoffset 会自动计算路径总长度。

小结

SVG 动画具有分辨率无损的特点,适合多种场景,配合 Anime.js 可实现轻量、流畅的图形动画。

示例演示

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

<head> <meta charset="UTF-8" /> <title>Anime.js SVG 动画示例</title> <style> svg { display: block; margin: 40px auto; width: 200px; height: 200px; }

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

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

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

</style> </head>

<body> <svg viewBox="0 0 200 200"> <path id="line" d="M20,100 Q100,20 180,100 Q100,180 20,100 Z" /> </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: ‘#line’, strokeDashoffset: [anime.setDashoffset, 0], easing: ‘easeInOutSine’, duration: 2000 }); }; </script> </body>

</html>