Measuring FPS with Canvas

This is actually a fairly simple one to do, though there is next to nothing on the web [at the moment] to show how it can be done, so since you’re here here you go. For the purpose of this article I’ll assume you already have canvas setup and a draw function of some kind. If you don’t, check this out, there is a sample of code at the bottom that has everything you’ll need to get started.

The first thing to do is setup some variables.

var drawInterval = 50;
var frameCount = 0;
var fps = 0;
var maxfps = 1 / (drawInterval / 1000);
var lastTime = new Date();

In the snippet above the first variable stores the draw interval, this needs to be used for the setInterval function that calls your draw function every n milliseconds.

// ...
setInterval(Draw, drawInterval);
// ...
// ...

The next two variables are easy enough. Frame count will hold a running count of how many frames we have drawn each second and FPS will store the current FPS the game is running at.

The third variable stores the maximum possible FPS the game can achieve at the current draw interval. This is basically the maximum number of times the draw function can be called within 1 second (1000 msec) under optimal conditions, for example in such cases were setInterval isn’t queuing due to high CPU usage in which case it will simple slow down. This slowdown possibility is why we need the final variable, last time, which will store the last time our FPS counter was updated.

So, onto calculating the FPS itself. At the top of your draw function that gets called by the setInterval function you will need the following.

var nowTime = new Date();
var diffTime = Math.ceil((nowTime.getTime() - lastTime.getTime()));
// ...
// ...

These two lines simply record the current time and find how long (in msec) it has been since the FPS counter was updated. If this is the first time the draw function is being run the initialization time we set above during declaration will be used. Immediately below these two lines add the following.

if (diffTime >= 1000) {
    fps = frameCount;
    frameCount = 0.0;
    lastTime = nowTime;
}

Here we first check if 1 second has passed since we last updated the FPS or not. If true, we set the FPS variable to the current frame count and then reset the frame counter itself so it can start counting for the next second. Before leaving set the last time variable to the current time to reset the time difference for the next draw loop.

Finally, at the end of your draw function you will need to increment the frame counter variable.

// ...
// ...
// ...
frameCount++;

And with that your done. Except you may want to see what FPS your game is running at. There are many ways to show this, you could, for example, simply update a HTML control on the page, set the document.title or even draw the value directly to the canvas screen like this.

ctx.save();
ctx.fillStyle = '#000000';
ctx.fillRect(0, height - 15, width, 15);
ctx.fillStyle = '#FFF';
ctx.font = 'bold 10px sans-serif';
ctx.fillText('FPS: ' + fps + '/' + maxfps, 4, height - 4);
ctx.restore();

This little snippet will draw a black bar at the bottom of your canvas window with white text showing the current FPS. You will need to make sure that the height and width variables are the values of your canvas elements height and width for it to work.

Putting it all together you should have something like this.

var ctx = null;
var width = 0, height = 0;
var drawInterval = 50;
var frameCount = 0;
var fps = 0;
var maxfps = 1 / (drawInterval / 1000);
var lastTime = new Date();

function init() {
    if (Setup('2d')) {
         setInterval(Draw, drawInterval);
    }
}

function Setup(method) {
    var canvas = document.getElementById('canvas');

    if (canvas && canvas.getContext) {
         width = canvas.width;
         height = canvas.height;

         ctx = canvas.getContext(method);
         return true;
    }

    return false;
}

function Draw() {
    var nowTime = new Date();
    var diffTime = Math.ceil((nowTime.getTime() - lastTime.getTime()));

    if (diffTime >= 1000) {
       fps = frameCount;
       frameCount = 0.0;
       lastTime = nowTime;
    }

    ctx.clearRect(0, 0, width, height);

    ctx.save();
    ctx.fillStyle = '#000000';
    ctx.fillRect(0, height - 15, width, 15);
    ctx.fillStyle = '#FFF';
    ctx.font = 'bold 10px sans-serif';
    ctx.fillText('FPS: ' + fps + '/' + maxfps, 4, height - 4);
    ctx.restore();

    frameCount++;
}
This entry was posted in Canvas, Javascript, Tutorial. Bookmark the permalink.

One Response to Measuring FPS with Canvas

  1. Pingback: Glacial Flame in full swing | Beakable

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>