<svg viewBox="0 0 100 100">
<line x1="0" x2="0" y1="0" y2="150" stroke="orange" stroke-width="5" stroke-dasharray="5">
<animate attributeName="stroke-dashoffset" to="10" dur="1s" fill="freeze" restart="never"
repeatCount="indefinite">
</animate>
</line>
</svg>
这段代码实现的功能是在SVG画布上绘制一条橙色的虚线,并且让这条虚线不断地重复移动。代码步骤解释:
1. <svg viewBox="0 0 100 100"> :创建一个SVG画布,指定了视口框的大小为100x100。
2. <line x1="0" x2="0" y1="0" y2="150" stroke="orange" stroke-width="5" stroke-dasharray="5"> :在SVG画布上绘制一条直线,起点坐标为(0,0),终点坐标为(0,150),颜色为橙色,宽度为5像素,虚线间隔为5像素。
3. <animate attributeName="stroke-dashoffset" to="10" dur="1s" fill="freeze" restart="never" repeatCount="indefinite"> :通过动画属性 stroke-dashoffset ,将虚线的偏移量逐渐变化到10,持续时间为1秒,动画结束后保持在最终状态,不重复播放。
。这样,代码就实现了在SVG画布上绘制一条橙色的虚线,并通过动画让虚线不断重复移动的效果。
以前都是借助CSS来实现,如下所示
其实在一些工控行业上,直接通过原始的SVG的动画元素做就已经够用了。
同样我们可以设置SVG圆形的描边动画,来创建类似预加载动画的效果。
<svg viewBox="0 0 1000 1000">
<circle cx="500" cy="500" r="200" stroke="red" fill="transparent" stroke-width="5" stroke-dasharray="20,20" stroke-dashoffset="20">
<animate
attributeName="stroke-dashoffset"
to="360"
dur="1s"
fill="freeze"
restart="never"
repeatCount="indefinite">
</animate>
</circle>
</svg>
当然,如果是需要风扇转动的效果,可以用另外的动画属性
<?xml version="1.0"?>
<svg
width="120"
height="120"
viewBox="0 0 120 120"
xmlns="http://www.w3.org/2000/svg"
version="1.1"
xmlns:xlink="http://www.w3.org/1999/xlink">
<polygon points="60,30 90,90 30,90">
<animateTransform
attributeName="transform"
attributeType="XML"
type="rotate"
from="0 60 70"
to="360 60 70"
dur="10s"
repeatCount="indefinite" />
</polygon>
</svg>
SVG描边动画 (codepen.io)
<svg viewBox="0 0 200 100" width="600" height="200">
<!-- the path to be animated along -->
<path fill="none" stroke="#4af"
d="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" />
<!-- the mover -->
<circle r="5" fill="#af4">
<animateMotion dur="6.6s" repeatCount="indefinite"
path="M20,50 C20,-50 180,150 180,50 C180-50 20,150 20,50 z" />
</circle>
</svg>
应用到实际项目中的效果