我希望点跟随鼠标光标,例如点击。代码看起来很简单,但每次单击时,点都会运行更短的距离并且不会到达目标。
问题是为什么?
代码在这里:
https://jsfiddle.net/thiefunny/ny0chx3q/3/
HTML
<circle r="10" cx="300" cy="300" />
JavaScript
const circle = document.querySelector("circle")
window.addEventListener("click", mouse => {
const animation = _ => {
let getCx = Number(circle.getAttribute('cx'))
let getCy = Number(circle.getAttribute('cy'))
circle.setAttribute("cx", `${getCx + (mouse.clientX - getCx)/10}`);
circle.setAttribute("cy", `${getCy + (mouse.clientY - getCy)/10}`);
requestAnimationFrame(animation)
}
requestAnimationFrame(animation)
});
编辑:对于这个任务,我需要 requestAnimationFrame(),而不是 CSS,因为这只是最简单的例子,但我想稍后为运动添加更多复杂性,包括多个点、随机参数等,就像我在这里所做的那样:https ://walanus.pl
我花了很多时间进行实验,但我唯一的结论是,在单击事件之后,我应该以某种方式取消当前动画并开始新的动画,以便为下一个动画重新开始。