如何在SVG路径动画启动前为可动画对象设置带间隔的初始位置?
SVG动画对象路径初始间隔排列实现方案
需要让SVG中的可动画对象(红色三角形、蓝色圆形)在开始沿指定路径移动前,按固定间隔排列在路径上,而非默认的初始原点位置。
实现思路
- 利用SVG路径API获取路径总长度,计算每个元素初始位置对应的路径进度
- 通过坐标计算将元素平移到路径上的指定点位
- 调整动画参数,确保动画从初始位置开始沿路径继续运动
修改后的完整代码
<button onclick="moveTriangle()">StartMove</button> <button onclick="pauseMove()">PauseMove</button> <button onclick="unPasueMotion()">ContinueMove</button> <svg id="container" viewBox="-10 -10 200 100" xmlns="http://www.w3.org/2000/svg" style="border:1px solid white"> <path id="motionPath" fill="none" stroke="gray" stroke-width="30" d="M20,50 L50,20 150,70 180,50" /> <polygon id="sym1" points="-10,0 0,10 10,0 0,-10" fill="red" /> <circle id="sym2" r="5" fill="blue"></circle> <animateMotion id="animation1" xlink:href="#sym1" dur="10s" repeatCount="1" fill="freeze" begin="indefinite" rotate="auto" keyPoints="0;1" keyTimes="0;1" calcMode="linear"> <mpath xlink:href="#motionPath"/> </animateMotion> <animateMotion id="animation2" xlink:href="#sym2" dur="10s" repeatCount="1" fill="freeze" begin="indefinite" rotate="auto" keyPoints="0.2;1" keyTimes="0;1" calcMode="linear"> <mpath xlink:href="#motionPath"/> </animateMotion> </svg> <script> var animation1 = document.getElementById("animation1"); var animation2 = document.getElementById("animation2"); var svg = document.getElementById("container"); function initPositions() { const path = document.getElementById('motionPath'); const totalLength = path.getTotalLength(); // 定位第一个元素到路径起点 const startPoint = path.getPointAtLength(0); document.getElementById('sym1').setAttribute('transform', `translate(${startPoint.x}, ${startPoint.y})`); // 定位第二个元素到路径20%的位置 const offsetPoint = path.getPointAtLength(totalLength * 0.2); document.getElementById('sym2').setAttribute('transform', `translate(${offsetPoint.x}, ${offsetPoint.y})`); } function moveTriangle() { animation1.beginElement(); animation2.beginElement(); } function unPasueMotion() { svg.unpauseAnimations(); } function pauseMove(){ svg.pauseAnimations(); } // 页面加载完成后初始化位置 window.onload = initPositions; </script>
关键代码说明
path.getTotalLength():获取目标路径的总像素长度,用于计算间隔比例path.getPointAtLength(length):返回路径上距离起点指定长度的坐标点,以此确定元素初始位置transform="translate(x,y)":将元素平移到路径上的目标坐标,因为元素自身以原点为中心,直接平移即可对齐路径点位keyPoints&keyTimes:定义动画的路径进度区间,比如第二个元素设置keyPoints="0.2;1",表示动画从路径20%的位置开始,到100%的位置结束calcMode="linear":确保动画进度与时间呈线性关系,避免运动速度不均
内容的提问来源于stack exchange,提问作者personax
相关产品推荐
相关产品推荐

