启动一个对象从一个随机点沿 SVG 路径移动 [英] Starting an object to move from a random point along an SVG path

查看:32
本文介绍了启动一个对象从一个随机点沿 SVG 路径移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里尝试深入了解 SVG.有什么方法可以沿着 SVG 路径移动圆,圆从由路径长度确定的特定点开始移动?例如,当对象到达终点时,它又从头开始.使用什么属性使圆从随机点移动,例如,从 from 20 开始而不是 0 to 100?SVG 中有直接 from 和 to,但我不确定如何正确使用它.此外,我发现 keytimes 在某些情况下很有用,但它没有产生预期的结果.

在这里你可以看到一个 SVG 的 HTML 沿着一条路径移动,它当前从头开始:

 

<g fill="none"stroke="black"stroke-width="1"><pathstroke-dasharray="3" id="motionpath2"d="M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80"/><circle class="circle2" r=8 fill=red ;z-index=55><animateMotion dur="2s" repeatCount="不确定"旋转=自动"从=20"到=100"><mpath href="#motionpath2"/></animateMotion></圆圈></svg>

解决方案

SVG 中有直接 from 和 to,但我不确定如何使用它正确.此外,我发现关键时间在某些情况下很有用,但它没有产生想要的结果.

可以不使用JS从路径上的任何一点开始SVG动画,但它的位置必须在代码中提前确定.

为此使用了一对属性.

keyPoints="0;1" - 从开始到结束的移动keyTimes="0;1"

keyPoints="0.5;1" - 从中​​间到最后的移动keyTimes="0;1"

keyPoints="1;0" - 从头到尾的移动keyTimes="0;1"

这种方式可以控制动画起点的位置,但是理论上不可能从随机选择的点创建动画,因为SVG中没有变量,没有数组,没有存储和执行的指令数学函数.

在下面的例子中,JS仅用于处理按下控制按钮的事件:

<button id="btn1" onclick="forwardSVG()">forward</button/><button id="btn2" onclick="middleSVG()">Middle</button/><button id="btn3" onclick="backSVG()">返回</button/>

<svg xmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink" height="160" width="360" ><g fill="none"stroke="black"stroke-width="1"><pathstroke-dasharray="3" id="motionpath2"d="M 10 80 C 40 10, 65 10, 95 80 S 150 150, 180 80"/><circle class="circle2" r=8 fill=red><动画动作id="转发"时间=2秒"开始=不确定"重复计数=1"关键点=0;1"keyTimes="0;1"calcMode="线性" ><mpath href="#motionpath2"/></animateMotion><动画动作id="中间"时间=2秒"开始=不确定"重复计数=1"keyPoints="0.5;1"keyTimes="0;1"calcMode="线性" ><mpath href="#motionpath2"/></animateMotion><动画动作id="返回"时间=2秒"开始=不确定"重复计数=1"关键点=1;0"keyTimes="0;1"calcMode="线性" ><mpath href="#motionpath2"/></animateMotion></圆圈></svg><脚本>var animation1 = document.getElementById("forward")函数 forwardSVG(){animation1.beginElement();}var animation2 = document.getElementById("middle")函数 middleSVG(){animation2.beginElement();}var animation3 = document.getElementById("back")函数 backSVG(){animation3.beginElement();}</script>

这里有一些没有JS的混乱字母运动错觉的例子