SVG动画实现方法全解

本篇介绍 SVG 动画的三种主流实现方式:SMIL、CSS、JavaScript。

一、SMIL 动画(基本废弃)

  • 简介:SVG 原生动画方案,直接在 SVG 标签内添加<animate>等元素
  • 常用标签<animate><animateTransform><animateMotion>
  • 示例
1
2
3
4
5
<svg width="120" height="80" xmlns="http://www.w3.org/2000/svg">
<circle cx="20" cy="40" r="15" fill="#4FC3F7">
<animate attributeName="cx" from="20" to="100" dur="2s" repeatCount="indefinite" />
</circle>
</svg>
  • 成品展示:

二、CSS 动画

  • 简介:通过 CSS 为 SVG 元素添加过渡或关键帧动画
  • 常用属性transitionanimation@keyframes
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
<svg width="120" height="80" xmlns="http://www.w3.org/2000/svg">
<rect id="css-rect" x="10" y="30" width="40" height="20" fill="#FFD54F" />
<style>
#css-rect {
animation: moveX 2s infinite alternate;
}
@keyframes moveX {
from { transform: translateX(0); }
to { transform: translateX(60px); }
}
</style>
</svg>
  • 成品展示:

三、JavaScript 动画

  • 简介:通过 JS 动态修改 SVG 属性实现动画,适合复杂交互
  • 常用 APIsetAttributerequestAnimationFrame
  • 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<svg id="js-ani" width="120" height="80" xmlns="http://www.w3.org/2000/svg">
<circle id="js-circle" cx="20" cy="40" r="15" fill="#E57373" />
<script><![CDATA[
let c = document.getElementById('js-circle');
let dir = 1, x = 20;
function animate() {
x += dir * 2;
if (x > 100 || x < 20) dir *= -1;
c.setAttribute('cx', x);
requestAnimationFrame(animate);
}
animate();
]]></script>
</svg>
  • 成品展示: