Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop an animation with Snap.svg

Background: I'm using Snap.svg to render a circle, then animate its radius on hover. I've got that piece working with the code below.

Problem: I'm trying to get a looping "pulse" effect once circleRadar is hovered on, which would involve continuously animating between the initial r and the new r of 70. While the docs' mention of snap.animate(from, to,...) here seems promising, I can't figure out how I would implement that in the context of my code. Is there anyone a little more familiar with Snap who can help? Thanks!

Code:

//create the circle
circleRadar = s.circle(195, 345, 20);

//initial styling  
circleRadar.attr({
  fill: "#3f8403",
  opacity: 0.3
});

//animation
function testRadar(){
  circleRadar.animate({
    opacity: '1',  
  r: 70
  }, 1000, mina.elastic);
}

//trigger
circleRadar.hover(testRadar);
like image 765
Marcatectura Avatar asked Dec 11 '22 09:12

Marcatectura


2 Answers

I suspect there may be a repeat function somewhere on Snap, but I couldn't see it, so if there is, that would probably be the way to go. In the absence of that, you could have 2 animations and switch between them. So...

var animating = true;

//animation
function animOn(){
  if( animating ) {
    circleRadar.animate({
      opacity: '1',  
        r: 70,
        fill: 'none'
    }, 1000, mina.elastic, animOut);
  };
}

function animOut() {
  circleRadar.animate({
      opacity: '0.3',  
      r: 20,
      fill: 'none'
   }, 1000, mina.elastic, animOn);
};

circleRadar.hover(function() { animating=true; animOn() },      
    function() { animating=false });

There's a fiddle here http://jsfiddle.net/TWBNE/29/ (I suspect the above may need tweaking, repeating animations can sometimes be a bit fiddly depending on mousemovements etc if you move out mid animation for example. So you may want not to allow a restart until anim is finished) . Another alternative could be making 2 animations that use the 'begin' attribute and start it on 'end' of the others id.

Edit: You may want to check for memory use if the animations are likely to be left for a very long time. Some Snap versions have worse memory use, and also this method doesn't complete functions, so I'm not 100% if it would increase the memory call stack. If its very quick animations it may be more noticable.

like image 78
Ian Avatar answered Dec 19 '22 13:12

Ian


I think snap.svg's animation system is too young and doesn't have that function. Current version is 0.0.1! :)

I think way to go for advanced animation is to connect it with Greensock Animation Platform, thats the most advanced animation framework that I know for the web. Have a look on this thread: http://forums.greensock.com/topic/8604-snapsvg/

Otherwise, you can call you animation again on complete.

like image 43
OndrejRohon Avatar answered Dec 19 '22 12:12

OndrejRohon