hfg-gmuend / gmynd

A utility library for working with data in Javascript
15 stars 1 forks source link

Stop animate function if fn returns false #3

Closed leoweigand closed 9 years ago

leoweigand commented 9 years ago

Added possibility to end animation by returning false from animation function. Excerpt from tests/cancel-animation-test.html:

var rect = createNode("rect", {
  x: 0, y:0,
  width: 100,
  height: 100
});
animate(function(frameCount) {
  if(frameCount == 500)
    return false;

  rect.setAttribute("x", frameCount);
});
bohnacker commented 9 years ago

It's good to have a possibility for stopping an animation. This seems to be a good start. I'm wondering if there would be another way where I could stop the animation and start it again?

leoweigand commented 9 years ago

Adding a possibility to stop and resume an animation might not be necessary. To implement a delay, you could simply do an if on the frameCount and continue when it has passed a certain value, for example. After all, the native Code animate is replacing can be reduced to this:

function animate(){
   // do stuff
   requestAnimationFrame(animate);
}
requestAnimationFrame(animate);

As this is all native code required to run an animation loop, abstracting too far away from that could be counterproductive.

phlsa commented 9 years ago

Well, you could simply call animate() again to restart the animation. This would probably reset the frame counter though. @sinuit, would that be sufficient for the scenarios you're imagining?

Another way would be to have explicit functions like pause(fn) and stop(fn) to control animations. That would make it harder to work with anonymous animation functions though.

leoweigand commented 9 years ago

animate() could also return an object that has a .start() and a .stop() method, that would eliminate the problem with anonymous functions

bohnacker commented 9 years ago

For now it should be enough to be able to stop the animation with returning false. @phlsa: I tried it, it also works to start the animation again with animate(). So I will merge this pull request. All in all I'm not really happy with the lots of different ways of doing animation in the web world. I'll try to summarize my concerns as a new issue.