Simple game/animation loop in HTML5 with FPS overlay

October 29, 2011 [ canvas | html | old ]

The following code is a really simple animation/simulation loop. In one corner the current frames per second (FPS) count is displayed. It does neither throttle the FPS, nor perform interpolation, nor skip ticks. If you are interested in more elaborate looping, you might want to take a look at this game loop article.

Assuming we have a HTML page, containing a canvas element with id=“cvs”, the looping is started by caling the init(); function (this is the boring, functional part of the code you probably won’t need to change).

var lastUpdate; // time in milliseconds of the last update
var FPS = 1; // current Frames per Second number will be saved here

var displayFPS = true; // do we want to display the FPS?
var ctx; // will hold the 2d context of our canvas

// initializes the loop and starts it		
function init() {
  var cvs = document.getElementById("cvs");				
  if (cvs.getContext) { // if the element is indeed a functional canvas
    ctx = cvs.getContext("2d");
    lastUpdate = new Date().getTime(); // initialize, so it is not null
    loop(); // start looping

function loop() {
  // compute dt - the time difference since the last update 
  var now = new Date().getTime();
  var dt = now-lastUpdate;
  lastUpdate = now;
  // no interpolation, just what the FPS seems like at the moment
  FPS = Math.floor(1000 / dt);
  update(dt); // update world / scene 
  draw(ctx); // draw it, context can be exchanged
  // indirect call to avoid hitting the max recursion depth
  setTimeout(loop, 1); 

The update and draw functions are where the actual fun will be - the simulation and visualization of the scene. At the end of the draw function doDisplayFPS is called which writes the current framerate into the lower right corner.

// deltaTime - amount of milliseconds since last update
function update(deltaTime) {
  // noop <- TODO: insert update calls for interesting stuff

// ctx - 2d context of a canvas element			
// where everything will be drawn on
function draw(ctx) {
  // background
  // black to make the element visible
  // clearRect might be more appropriate
  ctx.fillStyle = "black";
  ctx.fillRect(0,0,ctx.canvas.width, ctx.canvas.height);
  // <- TODO: insert interesting stuff draw calls
  //  draw the FPS overlay
  if (displayFPS) {

// writes the current framerate into the bottom right corner
// in big friendly red flickering letters
function doDisplayFPS(ctx) {
  ctx.fillStyle = "red";
  ctx.font = "20px sans-serif";
  ctx.textAlign = "right"
  ctx.textBaseline = "bottom";

Want to be notified when I publish new content?

Just enter your name and email below. You will also get content that I share exclusively with the list, and zero spam!