Skip to main content

动画标签

常用动画标签

  • < animate />
  • < animateTransform />
  • < animateMotion />
  • set

<animate>标签

<animate 
attributeName="属性名" // 要动画的属性(如 x、fill、opacity)
attributeType="XML/CSS" // 属性类型(默认自动检测)
from="初始值" // 起始值(可选)
to="结束值" // 结束值
values="值列表" // 多关键帧值(如 "0;50;30")
dur="时长" // 动画持续时间(如 2s、500ms)
begin="触发时机" // 开始条件(如 0s、click)
repeatCount="重复次数" // 数字或 indefinite(无限循环)
fill="freeze/remove" // 动画结束后的状态(默认恢复初始)
calcMode="插值模式" // discrete(离散)| linear(默认线性)| paced(匀速)| spline(贝塞尔)
keyTimes="时间点列表" // 控制关键帧时间比例(如 "0;0.5;1")
keySplines="贝塞尔曲线" // 与 calcMode="spline" 配合使用
/>

属性说明

属性作用示例值
attributeName指定要动画的属性(支持所有可被数值化的属性)"cx""fill""width"
from / to单值变化的起始和结束状态from="0" to="100"
values多关键帧值(分号分隔)values="0;50;30"
dur动画持续时间(单位:秒 s 或毫秒 msdur="3s"
begin触发时机(支持事件如 clickmouseover 或延时如 1sbegin="click"
repeatCount重复次数(indefinite 表示无限循环)repeatCount="5"
fill动画结束后的状态:freeze(保持结束值)或 remove(恢复初始,默认)fill="freeze"
calcMode插值模式,影响动画过渡效果calcMode="paced"

基础用例

1. 水平移动动画(单值变化)

<rect x="0" y="50" width="50" height="50" fill="blue">
<animate
attributeName="x"
from="0" to="250"
dur="2s"
repeatCount="indefinite"
/>
</rect>
  • 效果:矩形从 x=0 移动到 x=250,持续 2 秒并无限循环。

2. 颜色渐变(多关键帧)

<circle cx="100" cy="100" r="40">
<animate
attributeName="fill"
values="red;green;blue"
dur="4s"
repeatCount="indefinite"
/>
</circle>
  • 效果:颜色从红 → 绿 → 蓝循环变化,每个颜色过渡占 1.33 秒。

3. 点击触发动画

<rect width="100" height="100" fill="orange">
<animate
attributeName="opacity"
from="1" to="0"
dur="1s"
begin="click"
fill="freeze"
/>
</rect>
  • 效果:点击矩形后,透明度从 1 变为 0(淡出),并保持最终状态。

进阶用例

1. 贝塞尔曲线缓动效果

<circle cx="50" cy="50" r="20" fill="purple">
<animate
attributeName="cx"
from="50" to="250"
dur="2s"
calcMode="spline"
keyTimes="0;1"
keySplines="0.25 0.1 0.25 1" // 自定义缓动曲线(ease-in-out)
repeatCount="indefinite"
/>
</circle>
  • 效果:圆形水平移动,采用贝塞尔曲线实现平滑加速减速效果。

2. 路径动画(结合 <path>

<path d="M10 80 L110 80" stroke="black">
<animate
attributeName="d"
dur="3s"
values="M10 80 L110 80; M10 80 L50 10; M10 80 L110 80"
repeatCount="indefinite"
/>
</path>
  • 效果:线段从水平变为倾斜再恢复,形成动态折线。

3. 组合动画(多属性同步)

<rect x="0" y="0" width="50" height="50" fill="teal">
<!-- 同时改变位置和大小 -->
<animate attributeName="x" from="0" to="200" dur="3s" repeatCount="indefinite"/>
<animate attributeName="width" from="50" to="100" dur="3s" repeatCount="indefinite"/>
</rect>
  • 效果:矩形向右移动的同时宽度从 50 扩展到 100。

注意事项

  1. 兼容性:SVG 动画在部分旧浏览器(如 IE)中不支持,建议使用 CSS 动画作为补充。

  2. 性能优化:避免同时激活过多复杂动画,可能导致渲染卡顿。

  3. 同步控制:通过beginend 属性实现动画序列化:

    <animate id="anim1" .../>
    <animate begin="anim1.end" .../> // 在 anim1 结束后触发

通过灵活组合属性,<animate> 能实现从简单过渡到复杂交互的多样化动态效果。

<>