9. 轨迹动画
轨迹动画通过animateMotion
元素实现。直线轨迹动画不做介绍,这里对复杂的曲线路径进行演示
9.1 三次贝塞尔曲线轨迹
- 源码
<!-- 红线 -->
<path d="M50,125 C100,25 150,225 200,125" fill="none" stroke="red"></path>
<!-- 三角形 -->
<path d="M-10,-3 L10,-3 L0,-25z" fill="yellow" stroke="red">
<!-- 运动轨迹,同红线 -->
<animateMotion
path="M50,125 C100,25 150,225 200,125"
rotate="auto"
dur="6s"
repeatCount="indefinite"
fill="freeze"
></animateMotion>
</path>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
TIP
代码第10行,rotate设置为auto,三角形可根据轨迹实时改变旋转角度。rotate默认值为0
9.2 使用mpath实现
使用mpath
实现上例动画。mpath
为一种简写方法而已
- 源码
<path id="cubicCurve" d="M50,125 C100,25 150,225 200,125" fill="none" stroke="red"></path>
<path d="M-10,-3 L10,-3 L0,-25z" fill="yellow" stroke="red">
<animateMotion rotate="auto" dur="6s" repeatCount="indefinite" fill="freeze">
<mpath xlink:href="#cubicCurve"></mpath>
</animateMotion>
</path>
1
2
3
4
5
6
2
3
4
5
6
9.3 轨迹动画阶段控制
keyPoints
和keyTimes
同时使用来控制动画在轨迹上的运动速度
- 源码
<animateMotion
rotate="auto"
dur="6s"
keyPoints="0;0.25;0.9;1"
keyTimes="0;0.4;0.8;1"
calcMode="linear"
fill="freeze"
repeatCount="indefinite"
>
<mpath xlink:href="#cubicCurve"></mpath>
</animateMotion>
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
keyPoints
和keyTimes
依次对应;上例通俗来解释:三角形在前半段上坡途中(这段路程大概占总长度的25%),花掉了40%的时间