gpt4 book ai didi

svg - 沿 SVG 中的路径定位对象

转载 作者:行者123 更新时间:2023-12-05 00:58:00 24 4
gpt4 key购买 nike

我在 SVG 中有一个椭圆。

<ellipse cx="960" cy="600" rx="700" ry="480"/>

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

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

最佳答案

您可以使用 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)
})
svg{border:solid; width:300px;}
ellipse{fill:none;stroke:black;stroke-width:5px}
<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>

更新

OP 正在评论:

I should have warned that I can't use any javascript, I'm looking for a pure SVG solution. Sorry for that.

接下来是一个演示,我使用 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>

关于svg - 沿 SVG 中的路径定位对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58878090/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com