SVG 动画
SVG 动画
SVG 元素可以动画化。
在 SVG 中,我们有四个动画元素来设置或动画化 SVG 图形
-
<set>
-
<animate>
-
<animateTransform>
-
<animateMotion>
SVG <set>
<set>
元素用于在指定持续时间内设置属性的值。
在此示例中,我们创建一个红色圆圈,其半径初始为 25,3 秒后半径将设置为 50
这是 SVG 代码
示例
<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="25" style="fill:red;">
<set attributeName="r" to="50" begin="3s" />
</svg>
自己动手试一试 »
代码解释
<set>
元素中的attributeName
属性定义要更改的属性<set>
元素中的to
属性定义属性的新值<set>
元素中的begin
属性定义动画何时开始
SVG <animate>
<animate>
元素用于动画化元素的属性。
<animate>
元素应嵌套在目标元素内。
在此示例中,我们创建一个红色圆圈。我们动画化 cx 属性从 50 到 90%。这意味着圆圈将从左向右移动
这是 SVG 代码
示例
<svg width="100%" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="50" style="fill:red;">
<animate
attributeName="cx"
begin="0s"
dur="8s"
from="50"
to="90%"
repeatCount="indefinite" />
</circle>
</svg>
自己动手试一试 »
代码解释
attributeName
属性定义要动画化的属性begin
属性定义动画何时开始dur
属性定义动画的持续时间from
属性定义起始值to
属性定义结束值repeatCount
属性定义动画播放的次数
带冻结的 SVG <animate>
在此示例中,我们希望红色圆圈在到达最终位置时冻结(停止)(而不是弹回起始位置)
这是 SVG 代码
示例
<svg width="100%" height="100" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="50" style="fill:red;">
<animate
attributeName="cx"
begin="0s"
dur="8s"
from="50"
to="90%"
fill="freeze" />
</circle>
</svg>
自己动手试一试 »
代码解释
fill="freeze"
属性定义动画在到达最终位置时应冻结
SVG <animateTransform>
<animateTransform>
元素用于动画化目标元素的 transform
属性。
<animateTransform>
元素应嵌套在目标元素内。
在此示例中,我们创建一个将旋转的红色矩形
这是 SVG 代码
示例
<svg width="200" height="180" xmlns="http://www.w3.org/2000/svg">
<rect x="30" y="30" height="110" width="110" style="stroke:green;fill:red">
<animateTransform
attributeName="transform"
begin="0s"
dur="10s"
type="rotate"
from="0 85 85"
to="360 85 85"
repeatCount="indefinite" />
</rect>
</svg>
自己动手试一试 »
代码解释
attributeName
属性动画化<rect>
元素的transform
属性begin
属性定义动画何时开始dur
属性定义动画的持续时间type
属性定义变换的类型from
属性定义起始值to
属性定义结束值repeatCount
属性定义动画播放的次数
SVG <animateMotion>
<animateMotion>
元素设置元素沿运动路径的移动方式。
<animateMotion>
元素应嵌套在目标元素内。
在此示例中,我们创建一个矩形和一段文本。这两个元素都具有相同的路径 <animateMotion>
元素
这是 SVG 代码
示例
<svg width="100%" height="150" xmlns="http://www.w3.org/2000/svg">
<rect x="45" y="18" width="155" height="45" style="stroke:green;fill:none;">
<animateMotion
path="M0,0 q60,100 100,0 q60,-20 100,0"
begin="0s"
dur="10s"
repeatCount="indefinite" />
</rect>
<text x="50" y="50" style="font-family:Verdana;font-size:32">它是 SVG!
<animateMotion
path="M0,0 q60,100 100,0 q60,-20 100,0"
begin="0s"
dur="10s"
repeatCount="indefinite" />
</text>
</svg>
自己动手试一试 »
代码解释
path
属性定义动画的路径begin
属性定义动画何时开始dur
属性定义动画的持续时间repeatCount
属性定义动画播放的次数