使用 svg.js 循环动画

Loop animation with svg.js

本文关键字:动画 循环 js svg 使用      更新时间:2023-09-26

我有一个非常简单的svg动画.js只要页面打开,我就想循环运行。在浏览 github、文档或堆栈溢出页面时,我找不到任何东西。可以在此处找到没有循环的动画的工作版本。重要的js是:

//create the svg element and the array of circles
var draw = SVG('canvas').size(300, 50);
var circ = [];
for (var i = 0; i < 5; i++) {
    //draw the circles
    circ[i] = draw.circle(12.5).attr({
        fill: '#fff'
    }).cx(i * 37.5 + 12.5).cy(20);
    //first fade the circles out, then fade them back in with a callback
    circ[i].animate(1000, '<>', 1000 + 100 * i).attr({
        opacity: 0
    }).after(function () {
        this.animate(1000, '<>', 250).attr({
            opacity: 1
        });
    });
}

我知道如果没有 js 库,这很容易做到,但我只是使用 svg.js 的第一步。后来我计划将其用于更强大的动画。感谢您的任何建议或指示。

从 svg 的 0.38 版本开始.js在 loop() 方法内置:

https://github.com/wout/svg.js#loop

我还计划在即将发布的版本中创建一个reverse()方法。现在,loop()方法从头开始重新启动动画。

我不确定仅使用 svg.js 属性是否可行,因为从 svg 中不清楚.js它是否创建典型的 svg 动画元素。 无论如何,它可以通过循环来完成。 所以...

function anim( obj,i ) {
        obj.animate(1000, '<>', 1000 + 100 * i).attr({
            opacity: 0
        }).after(function () {
            obj.animate(1000, '<>', 250).attr({
                opacity: 1
            });
        });
};
function startAnims() {
   for( var i = 0; i< 5; i++ ) {
        anim( circ[i],i );
    }
    setTimeout( startAnims, 5000 ); // Or possibly setInterval may be better
};

jsfiddle 这里 http://jsfiddle.net/8bMBZ/7/因为不清楚它是否每次都在幕后添加元素(您可能希望存储动画,如果是这样,就开始它)。如果您需要,还有其他库与SVG的联系方式不同,例如Raphael,snap,d3,Pablo.js如果您需要从稍微不同的方式查看动画,您可以尝试作为替代方案。

我用来调用一个递归启动动画的函数。通过这种方式,我能够实现无限循环和反转。当然,您可以计数以避免无限循环,但总体思路如下:

 //custom animation function whose context is the element animated
function myCustomAnimation(pos, morph, from, to) {
    var currentVal = morph(from, to); //do morphing and your custom math
    this.attr({ 'some prop': currentVal });
}
var animationStart = 0; //just extra values for my custom animation function
var animationEnd = 1; //animation values start at 0 and ends at 1
line.attr({ 'stroke-width': 2, stroke: 'red' });
animateMeRepeatedly.apply(line);
function animateMeRepeatedly()
{
    this.animate(1500)
        .during(function (pos, morph) {
            myCustomAnimation.apply(this, [pos, morph, animationStart, animationEnd]);
        })
        .after(function () {
            this.animate(1500).during(function (pos, morph) {
                myCustomAnimation.apply(this, [pos, morph, animationEnd, animationStart]);
            }).after(animateMeRepeatedly);
        });
}