外观
SVG 演示二阶贝塞尔曲线
演示二阶贝塞尔曲线的运动轨迹,只需用 svg 的 <text>、<line>、<circle> 等基础元素,动画效果则用 <animate>、<animateMotion> 元素。
控制点和曲线
画布上用 <circle> 画出 3 个控制点,虚线可以用 <line> 来画,但后续的动画需要用到虚线的路径,所以选择用 <path> 标签,而贝塞尔曲线则用 <path> 的 Q 命令来绘制。
html
<svg width="320" height="320" viewBox="0 0 320 320" style="background: #efefef">
<path
d="M20 300 L160 20"
stroke="#bbb"
stroke-width="1"
stroke-dasharray="5 5"
/>
<path
d="M160 20 L300 300"
stroke="#bbb"
stroke-width="1"
stroke-dasharray="5 5"
/>
<path d="M20 300 Q160 20 300 300" stroke="#bbb" fill="none"/>
<circle cx="20" cy="300" r="5" fill="#bbb" />
<circle cx="160" cy="20" r="5" fill="#bbb" />
<circle cx="300" cy="300" r="5" fill="#bbb" />
</svg>控制点移动
<animateMotion> 是 svg 用于创建沿路径运动的动画元素,元素将沿着指定的路径进行移动。
在 <cricle> 内使用 <animateMotion> 即可让控制点按指定轨迹移动,<animateMotion> 的 path 属性可指定运动轨迹,也可用 <mpath> 子元素来引用外部路径,给 <path> 定义 id 并让 <mpath> 引用,即可让新增的 3 个控制点按已有的 3 个 <path> 路径来移动。
<animateMotion> 属性:
- dur,动画持续时间,如 5s、500ms。
- begin,动画何时开始,可以是时间值,如 5s,也可是 click、hover 等表示事件的字符串。
- end,动画何时结束。
- repeatCount,动画重复次数,具体数字或
indefinite无限重复。 - repeatDur,指定动画重复的总时长,
repeatDur="10s"表示 10 秒内一直重复。 - fill,动画结束后元素的状态,
freeze保持最终状态,remove跳回到初始状态。 - restart,动画是否可被重新启动,
always任何时候都可,whenNotActive不播放时可,never不可。 - path,设置运动轨迹。
- values,坐标序列,不使用
path时可用此属性设置运动轨迹。 - rotate,控制元素运动过程中的旋转方式,数字则为固定角度偏移,
auto为自动旋转以匹配路径切线方向,auto-reverse为自动反向旋转。
html
<path id="quadraticBezier" d="M20 300 Q160 20 300 300" />
<circle r="5" fill="#f03752">
<animateMotion begin="0" dur="6s" repeatCount="indefinite">
<mpath href="#quadraticBezier"></mpath>
</animateMotion>
</circle>控制点连线
连接正在移动的两个绿点形成绿线,如果用 <animateMotion> 来实现,将要经历很复杂的计算才能知道绿线的运行轨迹,但用 <animate> 就只需指定线段左端点的起点终点坐标和右端点的起点终点坐标,中间变化的状态交给计算机补充完成,这类似于 css 的过渡属性。
<animate> 属性:
- attributeName,指定要做动画的属性名称,必需。
- dur,动画持续时间。
- begin,动画何时开始。
- end,动画何时结束。
- from,指定属性的起始值。
- to,指定属性的结束值。
- by,指定属性的相对偏移量,会与
from相加,不能与to同时使用。 - repeatCount,动画重复次数。
- repeatDur,指定动画重复的总时长。
- restart,动画是否可被重新启动。
- fill,动画结束后属性的最终状态。
- values,分号分隔的值列表,用于定义关键帧。
html
<line stroke="#00c44d" stroke-width="1">
<animate
attributeName="x1"
from="20" to="160"
begin="0" dur="6s"
repeatCount="indefinite"
/>
<animate
attributeName="y1"
from="300" to="20"
begin="0" dur="6s"
repeatCount="indefinite"
/>
<animate
attributeName="x2"
from="160" to="300"
begin="0" dur="6s"
repeatCount="indefinite"
/>
<animate
attributeName="y2"
from="20" to="300"
begin="0" dur="6s"
repeatCount="indefinite"
/>
</line>注意事项
- 最后再用
<text>标签添加控制点名称,为了让控制点和名称一起移动,使用<g>分组元素将两者包裹一起做轨迹动画。 - 不能同时使用几何属性(如
cx/cy)和运动变换(如animateMotion)来控制位置,两者同时存在时,浏览器会选择前者作为定位方式,所以会出现动画不生效的情况。如果需要设置初始位置,可以考虑使用<animateTransform>。 - 动画元素最好都加上
begin属性,即便是将值定为0s,否则可能出现动画延迟播放的情况。 - SVG 里后面出现的元素层级会比前面的高,所以如果出现遮挡问题,调整下元素顺序即可。
- 在曲线上伸展的红线需要用 SVG 描边动画。