Snap SVG animate SVG on hover / reset SVG on leave

traummaschine picture traummaschine · May 1, 2014 · Viewed 8.9k times · Source

I'm using Snap.svg to create some SVGs that animate on hover.

A very simplified jsfiddle is here:

http://jsfiddle.net/62UA7/2/

var s = Snap("#svg");
var smallCircle = s.circle(100, 150, 70);

//animation
function animateSVG(){
    smallCircle.animate({cy: 300}, 5000,mina.bounce);
    smallCircle.animate({fill:"red"},200);
}

//reset function?
function resetSVG(){
    // something here to reset SVG??
}

smallCircle.mouseover(animateSVG,resetSVG);

The hover / animation is working fine.

The intention is to stop the animation and return to original SVG state if the user moves the mouse off the SVG - and this is where I'm currently stuck.

The actual SVG files I'm using are complex, so hoping for a quick way of 'refreshing' the SVG rather than manually moving it back to original position and colour

I'm assuming there's a really easy way of doing this - just can't seem to work it out or find the answer in any documentation anywhere.

Hopefully someone can help - thanks in advance if you can!

Answer

nathanel picture nathanel · May 27, 2014

If you are only willing to animate between 2 states I found that Codrops animated svg icons did great job with handling this type of snap.svg animations. I have started using their code as a basis for my future exploration of SNAP.SVG. But getting back to the code: the most fun part is that you configure your animation with simple JSON objects such as:

plus : { 
    url : 'plus',
    animation : [
        { 
            el : 'path:nth-child(1)', 
            animProperties : { 
                from : { val : '{"transform" : "r0 32 32", "opacity" : 1}' }, 
                to : { val : '{"transform" : "r180 32 32", "opacity" : 0}' }
            } 
        },
        { 
            el : 'path:nth-child(2)', 
            animProperties : { 
                from : { val : '{"transform" : "r0 32 32"}' }, 
                to : { val : '{"transform" : "r180 32 32"}' }
            } 
        }
    ]
},

and you can easily attach any sort of event trigger for animation In/Out. Hope that helps.