使用 SMIL 的 SVG 动画
同步多媒体集成语言 (SMIL) 是一种基于 XML 的语言,用于编写交互式多媒体演示文稿。作者可以在其他基于 XML 的语言中使用 SMIL 语法来定义动画元素的计时和布局。
SMIL 允许您
以下各节将展示如何在 SVG 中将 SMIL 用于这四种用例。
为元素的属性设置动画
以下示例为圆的 cx
属性设置动画。为此,我们在 <circle>
元素内添加了一个 <animate>
元素。对于 <animate>
来说,重要的属性是
如果您想在同一个元素内为更多属性设置动画,可以添加更多的 <animate>
元素。
<svg width="300" height="100">
<title>Attribute Animation with SMIL</title>
<rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
<circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1">
<animate
attributeName="cx"
from="0"
to="500"
dur="5s"
repeatCount="indefinite" />
</circle>
</svg>
为 transform 属性设置动画
<animateTransform>
元素允许您为 transform 属性设置动画。此元素是必需的,因为我们不是在为像 x 这样的单个数值属性设置动画。旋转属性看起来像这样:rotation(theta, x, y)
,其中 theta
是以度为单位的角度,x
和 y
是绝对位置。在下面的示例中,我们为旋转中心和角度设置了动画。
<svg width="300" height="100">
<title>SVG SMIL Animate with transform</title>
<rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
<rect
x="0"
y="50"
width="15"
height="34"
fill="blue"
stroke="black"
stroke-width="1">
<animateTransform
attributeName="transform"
begin="0s"
dur="20s"
type="rotate"
from="0 60 60"
to="360 100 60"
repeatCount="indefinite" />
</rect>
</svg>
跟随路径的动画
<animateMotion>
元素允许您根据路径来为元素的位移和旋转设置动画。路径的定义方式与 <path>
相同。您可以设置属性来定义对象是否会沿着路径的切线方向旋转。
示例 1:直线运动
在此示例中,一个蓝色圆圈在一个黑色框的左右边缘之间来回弹跳,无限循环。这里的动画由 <animateMotion>
元素处理。在这种情况下,我们建立了一个路径,该路径由一个 MoveTo 命令定义动画的起点,然后是 Horizontal-line 命令将圆向右移动 300 像素,接着是 Z command,它会闭合路径,建立一个回到起点的循环。通过将 repeatCount 属性的值设置为 indefinite
,我们指示动画应该永远循环,只要 SVG 图像存在。
<svg xmlns="http://www.w3.org/2000/svg" width="300" height="100">
<title>SVG SMIL Animate with Path</title>
<rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
<circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1">
<animateMotion path="M 0 0 H 300 Z" dur="3s" repeatCount="indefinite" />
</circle>
</svg>
示例 2:曲线运动
与上一个示例相同,但使用曲线路径并跟随路径方向。
<svg width="300" height="100">
<title>SVG SMIL Animate with Path</title>
<rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" />
<rect
x="0"
y="0"
width="20"
height="20"
fill="blue"
stroke="black"
stroke-width="1">
<animateMotion
path="M 250,80 H 50 Q 30,80 30,50 Q 30,20 50,20 H 250 Q 280,20,280,50 Q 280,80,250,80Z"
dur="3s"
repeatCount="indefinite"
rotate="auto" />
</rect>
</svg>