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

时间:2015-01-17 23:20:21

标签: javascript animation svg snap.svg

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

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()时(无论是在动画句柄还是元素上),我都会继续获得回调,直到浏览器冻结为止。

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

1 个答案:

答案 0 :(得分:1)

我读了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);