Search code examples
javascriptanimationkineticjsframe-raterequestanimationframe

Animation, FPS, and KineticJS


So I have a little game of a ball moving around on the screen and I would like to calculate the FPS. I am using KineticJS (4.3.1) which utilizes requestAnimationFrame under the hood.

      var anim = new Kinetic.Animation(
          function(frame) {

            //game logic
               //move ball
               //check collisions - if collision occurs, stop animation
               //redraw 

          }
      }

The 'frame' object has a time property which can be accessed with frame.time which measures the time since the animation was first started in milliseconds.

     var timeSinceAnimationStarted = frame.time;

What would be an accurate way of measuring the FPS?


Solution

  • A simple implementation, with "frames in a 1s interval". You can smoothen it out using, say, frames in a 5s interval

    // variables accessible from within function(frame)
    var frameCount = 0;
    var currentSecond = 0;
    var frameRate = 0;
    
    // within function(frame), called with current time on each new frame
    function updateFrameRate(time) {
        var second = Math.floor(time / 1000); // ms to integer seconds
        if (second != currentSecond) {
           frameRate = frameCount;
           frameCount = 0;
           currentSecond = second;
        }
        frameCount ++;
    }