gpt4 book ai didi

javascript - Snap.svg 动画 stop() 不会停止动画

转载 作者:行者123 更新时间:2023-12-03 11:02:47 25 4
gpt4 key购买 nike

我正在尝试沿一条路径制作一个简单的动画,该动画在元素到达窗口边界时停止。这是一些示例代码:

var s = Snap("#bouncy");

var ball = s.circle(100, 100, 10);
var mypath = getLinearPath({x: 300, y: 300}, {x: 300, y: -1000});

var windowBBox = s.getBBox();

function animateAlongPath(path, element, start, dur) {
var len = Snap.path.getTotalLength(path);
console.log(element);
ball.current_anim = Snap.animate(start, len, function (value) {
var movePoint = Snap.path.getPointAtLength(path, value);
var ballBounds = element.node.getBoundingClientRect();

if (Snap.path.isPointInsideBBox(windowBBox, movePoint.x, movePoint.y)) {
console.log("moving to ", movePoint);
var t = new Snap.Matrix();
t.translate(movePoint.x, movePoint.y);
element.transform(t);
} else {
console.log("stopping");
this.stop();
element.stop();
ball.current_anim.stop();
}
}, dur);
};

function getLinearPath(start, end) {
var p;
p = s.path("M " + start.x + " " + start.y + " L " + end.x + " " + end.y);
return p
};

animateAlongPath(mypath, ball, 0, 1000);

我只是想在球到达窗框顶部时停止动画。但是,当调用 stop() 时(无论是在动画句柄上还是在元素上),我都会继续收到回调,直到浏览器卡住为止。

如何取消动画并防止将来回调?

最佳答案

我阅读了 Snap.svg 的源代码,发现 anim.stop 调用了自己的回调函数。因此在动画回调中调用 stop 方法会导致无限循环。

要解决这个问题,您可以定义临时变量来阻止像这样的无限循环。

var s = Snap("#bouncy");

var ball = s.circle(100, 100, 10);
var mypath = getLinearPath({x: 300, y: 300}, {x: 300, y: -1000});

var windowBBox = s.getBBox();

function animateAlongPath(path, element, start, dur) {
var len = Snap.path.getTotalLength(path);
console.log(element);
ball.current_anim = Snap.animate(start, len, function (value) {
var movePoint = Snap.path.getPointAtLength(path, value);
var ballBounds = element.node.getBoundingClientRect();

if (Snap.path.isPointInsideBBox(windowBBox, movePoint.x, movePoint.y)) {
console.log("moving to ", movePoint);
var t = new Snap.Matrix();
t.translate(movePoint.x, movePoint.y);
element.transform(t);
} else {
console.log("stopping");
//this.stop();
//element.stop();

//NOTE: ball.current_anim.stop calls ball.current_anim
var anim = ball.current_anim;
delete ball.current_anim;
if(anim){anim.stop();}
}
}, dur);
};

function getLinearPath(start, end) {
var p;
p = s.path("M " + start.x + " " + start.y + " L " + end.x + " " + end.y);
return p
};

animateAlongPath(mypath, ball, 0, 1000);

关于javascript - Snap.svg 动画 stop() 不会停止动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28005424/

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