Search code examples
javascriptsnap.svgsvg-animate

Snap svg Snap.animation() function


I'm trying to create an animation with many stage of changes, does Snap.animation() allow to do that or i have to use css3 animation ? feel like the docs still missing something


Solution

  • The best way is to create a sequencing function or plugin that takes your animations in turn, without needing to code every one. You can pass these in as an array for example. Here is some code I have done previously.

    In the array, you pass it an object..

    el: the element to act on

    animation: The animation to perform (eg an object containing attributes to animate to)

    dur: The duration

    easing: The easing

    startFunc: An optional callback to run for each 'frame'.

    Note, you could probably include some blank frames (animate a attribute to the same value or one that doesn't exist or doesn't matter) if you wanted things like delays.

    function nextFrame ( frameArray,  whichFrame ) {
        if( whichFrame >= frameArray.length ) { return }
    
        if( typeof frameArray[ whichFrame ].startFunc === 'function' ) { 
          frameArray[ whichFrame ].startFunc.call(frameArray[ whichFrame ].el) 
        };
    
        frameArray[ whichFrame ].el.animate(    frameArray[ whichFrame ].animation, 
                        frameArray[ whichFrame ].dur, 
                        frameArray[ whichFrame ].easing,
                        nextFrame.bind(null,  frameArray, whichFrame + 1 ) 
        );
    
    }
    
    
    // Example of use
    
    var r = s.rect(100,100,100,100,20,20).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'red' });
    var c = s.circle(50,50,50).attr({ stroke: '#123456', 'strokeWidth': 20, fill: 'blue' });
    
    var g = s.group(r,c);
    
    var myFrames = [
        {   el: g,  animation: { transform: 'r360,150,150' }, dur: 1000, easing: mina.bounce },
        {   el: r,  animation: { transform: 't100,-100s2,3', fill: 'green' }, dur: 1000, easing: mina.bounce },
        {   el: r,  animation: { transform: 't100,100' }, dur: 1000, easing: mina.bounce, startFunc: sayHello },
        {   el: g,  animation: { transform: 's2,1' }, dur: 1000, easing: mina.bounce },
        {   el: r,  animation: { transform: 's1,2' }, dur: 1000, easing: mina.bounce },
        {   el: c,  animation: { transform: 's1,1' }, dur: 1000, easing: mina.bounce }];
    
    nextFrame( myFrames, 0 );
    
    function sayHello() {
        alert('hello, this is me ==> ' + this);
    }
    

    example