沿 SVG 中的路径定位对象

Zof*_*ren 2 svg

我在 SVG 中有一个椭圆。

<ellipse cx="960" cy="600" rx="700" ry="480"/>
Run Code Online (Sandbox Code Playgroud)

<path>如果需要,可以在 a 中绘制相同的形状。

是否可以沿着这条路径精确定位一个对象(例如一个圆),路径的角度或百分比?

enx*_*eta 6

您可以使用该getPointAtLength()方法获取路径上某个点的位置。如果要使用百分比,则需要计算路径的长度(使用getTotalLength()方法)

//the total length of the ellipse path
let ellTotalLength = ell.getTotalLength();
// the percentage as the input type range value 
let perc = itr.value / 100;



function setPosition(perc){
//the distance on the path where to place the little circle
let dist = ellTotalLength * perc; 
//get the position of a point at the distance dist on the path 
let point = ell.getPointAtLength(dist);
// set the values of the cx and cy attributes of the little circle
circ.setAttributeNS(null, "cx", point.x);
circ.setAttributeNS(null, "cy", point.y);  
}


setPosition(perc)

itr.addEventListener("input",()=>{
  perc = itr.value / 100;
  setPosition(perc)
})
Run Code Online (Sandbox Code Playgroud)
svg{border:solid; width:300px;}
ellipse{fill:none;stroke:black;stroke-width:5px}
Run Code Online (Sandbox Code Playgroud)
<p><input id="itr" type="range" value="70" /></p>
<svg viewBox="0 0 2000 1200">
  <ellipse id="ell" cx="960" cy="600" rx="700" ry="480" />
  <circle id="circ" r="30" fill="red" />
</svg>
Run Code Online (Sandbox Code Playgroud)

更新

OP 正在评论:

我应该警告说我不能使用任何 javascript,我正在寻找一个纯 SVG 解决方案。对不起。

接下来是一个演示,我使用 SVG 动画在椭圆上移动小圆圈。我已经改变了路径中的椭圆,我正在使用<animateMotion>动画为椭圆上的小圆圈设置动画,该动画的持续时间为 10 秒,但在 3 秒后停止,这意味着圆圈在 30% 的长度处停止。如果您需要立即执行此操作,您可以使用非常短的持续时间——例如dur=".1s" end=".03s"

我希望这是你所需要的。

<svg viewBox="-1000 -600 2000 1200">
<path id="path" d="M-700,0 a700,480 0 1,1 1400,0a700,480 0 1,1 -1400,0" style="stroke: #00f;stroke-width:20; fill: none;">
</path>
 <circle r="20" fill="red" id="circ">
 <animateMotion begin="0s" dur="10s" end="3s" rotate="auto" fill="freeze" >
 <mpath xlink:href="#path"></mpath>
 </animateMotion>
 </circle>
</svg>
Run Code Online (Sandbox Code Playgroud)