Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I recently got into using the HTML5-requestAnimationFrame-API a lot on animation-heavy websites, especially after seeing the Jank Busters talk. This seems to work pretty well and really improve performance in many cases.

Yet one question still persists for me: When wanting to use an animation that is NOT entirely calculated (think spritesheets for example) you will have to aim for a fixed frame rate. Of course one could go back to use setInterval again, but maybe there are other ways to tackle this.

The two ways I could think of using requestAnimationFrame with a fixed frame rate are:

var fps = 25; //frames per second

function animate(){

   //actual drawing goes here
   setTimeout(function(){
      requestAnimationFrame(animate);
   }, 1000 / fps)

}

animate();

or

var fps = 25; //frames per second

var lastExecution = new Date().getTime();

function animate(){

    var now = new Date().getTime();

    if ((now - lastExecution) > (1000 / fps)){
        //do actual drawing
        lastExecution = new Date().getTime();
    }

    requestAnimationFrame(animate);

}

animate();

Personally, I'd opt for the second option (the first one feels like cheating), yet it seems to be more buggy in certain situations.

Is this approach really worth it (especially at low frame rates like 12.5)? Are there things to be improved? Is there another way to tackle this?

share|improve this question
1  
Not entirely related to the question but still useful: take a look at Date.now(). –  Florian Margaine Nov 15 '12 at 13:08
    
@FlorianMargaine Great, thanks! –  m90 Nov 15 '12 at 14:01
add comment

2 Answers 2

up vote 1 down vote accepted

Your animation should be calculated even if that calculation is entirely a function of time. And at any given time you should be able to draw() an [animated] image and know that you're getting the right frame. You want something like this, but not necessarily this:

// whatever your "attributes" looks like, the point is you've given enough
// information to the constructor to find ordered frames in the image and know
// the framerate
function SpriteAnimation(image, attributes) {

  // you probably want a SpriteFrame "class" to populate here, based on whatever
  // existing code you use to extract frames from the sprite
  this.frames = [ SpriteFrame, SpriteFrame, ... ];
                         // ... getFramesFromImageAndAttributes(image, attributes)

  // if the animation is running, this is the time it started
  this.startTime = 0;

  // whatever your framerate is ... 
  this.fps = 25;         // getFPSFromAttributes(frame_attributes)

  // whether the animation loops infinitely
  this.loop = true;      // getLoopFlagFromAttributes(frame_attributes)

  // for canceling the animationframe request, if necessary
  this.animationFrameRequestId = null;

  // draw whichever frame should be visible *right now*
  this.draw = function() {

    // unconditionally show the first frame if the animation isn't running
    if (this.startTime == 0) {
      this.frames[0].draw();
      return;
    }

    // there may be a better and more accurate way to compute this ...
    var frame_duration = 1000 / this.fps;
    var now = (new Date()).getTime();
    var elapsed_time = now - this.startTime;
    var visible_frame = Math.floor(elapsed_time / frame_duration);

    if (visible_frame_number > frames.length) {
      if (!this.loop) {
        // we're past the end of the animation and we're not looping.
        // stop the animation.
        this.startTime = 0;
        visible_frame = 0;
      }
    }

    this.frames[visible_frame % frames.length].draw();

    if (this.startTime != 0) {
      var _t = this;
      requestAnimationFrame(_t.draw);
    }

  }

  this.animate = function() {
    this.startTime = (new Date()).getTime();
    var _t = this;
    requestAnimationFrame(_t.draw);
  }

  this.stop = function() {
    this.startTime = 0;
    if (this.animationFrameRequestId) {
      cancelAnimationFrame(this.animationFrameRequestId);
    }
  }

}

var a = new SpriteAnimation("/path/to/image.jpeg", {
  fps: 25,
  frame_width: 100,
  frame_height: 100,
  image_width: 1000,
  image_height: 10000
});
a.animate();

... Or whatever.

share|improve this answer
    
+1, great answer! –  m90 Aug 13 '13 at 18:57
add comment

For seamless animations, even sprite based use the second option, with Date.now(). Dont forget about

Return value

requestID is a long integer value that uniquely identifies the entry in the callback list. This is a non-zero value, but you may not make any other assumptions about its value. You can pass this value to window.cancelAnimationFrame() to cancel the refresh callback request.

(from MDN )

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.