svg的动画有四种不同形式展示,在svg中可以将以下元素作为动画的原材料
- 将元素的数值属性作为动画(比如一个圆的坐标x,y、半径r)
- 将变形属性作为动画
- 将颜色作为动画
- 按照路径运动
1、animation
每个svg元素需要多中动画只需要添加多个animation标签
- attributName动画的属性名称(元素的坐标、半径、宽高、填充颜色等属性)
- from初始
- to动画的结束
- dur动画的时间
- repeatCount动画的次数(取值是大于0的数字或者indefinite)
<svg width="800px" height="800px">
<rect x="0" y="0" width="200" height="100" fill="yellow"></rect>
<circle cx="50" cy="50" r="0" stroke="black" stroke-width="1" fill="none">
<animate
attributeName="r"
from="10"
to="30"
dur="2"
repeatCount="indefinite"></animate>
<animate
attributeName="fill"
from="red"
to="blue"
dur="2"
repeatCount="indefinite"></animate>
</circle>
</svg>
2、aniamteTransform
- from和to的值为(angle,x,y)angle表示旋转的角度,x,y的是一个旋转的坐标点,下面的列子是围绕一个绝对的坐标点旋转360,此时的旋转中心是固定不变,若改变x,y的值旋转中心就会移动
<polygon points="100,100 50,200 150,200" fill="RGB(0,255,255)">
<animateTransform
attributeType="XML"
attributeName="transform"
type="rotate"
from="0 150 200"
to="360 150 200"
dur="5"
begin="0"
repeatCount="indefinite">
</animateTransform>
</polygon>
3、animateMotion路径动画
将一个元素绑定到特定的路径上运动有两种方式,一是直接在animateMotion标签使用path绑定运动轨迹
另一种是在animateMotion内使用
<mpth xlink:href="#pathId"/>
- rotate表示运动目标的切线方向,有三个值none、auto、auto-reverse
- xlink:href=""表示动画链接的目标
- begin表示动画开始的方式可以规定时间或点击方式或者是在某个元素运动前后运动,取值方式如下
<!-- 路径 -->
<path id="p" d="M400 200 Q400,100 500,200 T600,220 700,220" fill="none" stroke="blue" stroke-width="1"></path>
<!-- 运动的圆 -->
<circle id="circle" cx="0" cy="0" r="10" fill="yellow"/>
<!-- 动画 -->
<animateMotion dur="5" repeatCount="indefinite" xlink:href="#circle">
<mpath xlink:href="#p"></mpath>
</animateMotion>
另一种写法
注意这里的path路径与上面#p路径是相同的坐标
<animateMotion
dur="3"
repeatCount="indefinite"
xlink:href="#circle"
rotate="auto-reverse"
path="M400 200 Q400,100 500,200 T600,220 700,220">
</animateMotion>