前言
SVG动画能够实现和CSS3动画类似的效果,除此之外还能够实现强大的路径动画,也就是使物体按照一定的路径移动。
SVG 动画元素介绍
svg可以设置动画的元素有5个,分别为 <set> <animate> <animateColor> <animateTransform> <animateMotion>
接下来我们具体来看看每一个元素的作用:
set
set用于设置属性值,可以用于实现延迟设置功能,也就是可以在特定时间之后修改某个属性值。
<svg height="400" width="400">
<g>
<text font-family="microsoft yahei" font-size="120" y="160" x="160">
动
<set attributeName="x" attributeType="XML" to="60" begin="3s" />
</text>
</g>
</svg>
这里的attributeName是定义要设置的属性,attributeType是定义要设置属性的类型,to为定义的值,begin为延迟时间。
animate
实现基础动画,跟css3中的animation类似。
<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px">
<rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" fill="yellow"/>
<circle cx="0" cy="50" r="15" fill="blue" stroke="black" stroke-width="1">
<animate attributeName="cx" from="0" to="300" dur="5s" repeatCount="indefinite" />
</circle>
</svg>
animateColor
用于设置颜色的动画,不过颜色动画使用animate也可以实现,所以这个属性已经被废弃。
animateTransform
用于实现样式过渡动画,类似于css3中的transition属性。
<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="200px">
<rect x="0" y="0" width="200" height="200" fill="yellow" stroke="red" stroke-width="1" />
<rect x="20" y="50" width="15" height="34" fill="blue" stroke="black" stroke-width="1" transform="rotation">
<animateTransform attributeType="XML" attributeName="transform" begin="0s" dur="5s" type="rotate" from="20 60 60" to="360 100 60" repeatCount="indefinite" />
</rect>
</svg>
animateMotion
animateMotion 元素可以用于定义SVG路径动画。
<svg xmlns="http://www.w3.org/2000/svg" width="300px" height="100px">
<rect x="0" y="0" width="300" height="100" fill="yellow" stroke-width="1" stroke="red" />
<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>
自由组合
自由组合也就是设置多个样式的动画,比方说同时设置位置和透明度的变化。只需设置多个animate即可。
<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg">
<g>
<rect width="90" height="90" fill="yellow" >
<animate attributeName="x" from="160" to="60" begin="0s" dur="3s" repeatCount="indefinite" />
<animate attributeName="opacity" from="1" to="0" begin="0s" dur="3s" repeatCount="indefinite" />
</rect>
</g>
</svg>
总结
一般除了路径动画,我们比较少使用svg animate来做动画。svg同样也可以使用css3的动画属性来设置动画。用css3比较方便。特别是多个样式的动画