Kontra​.gameLoop(​properties)

properties {object}
Properties of the game loop.
properties.update {function}
Function called every frame to update the game.
properties.render {function}
Function called every frame to render the game.
properties.fps {number}
Optional. Desired frame rate. Defaults to 60.
properties.clearCanvas {boolean}
Optional. Clear the canvas every frame before the render function is called. Defaults true.

The game loop updates and renders the game every frame. The game loop is not run until the gameLoops start() function is called.

The game loop uses a time-based animation with a fixed dt to avoid frame rate issues. Each update call is guaranteed to equal 1/60 of a second.

This means that you can avoid having to do time based calculations in your update functions and instead do fixed updates.

let loop = kontra.gameLoop({
  fps: 30,              // run the game at 30FPS
  clearCanvas: false,   // don't clear the canvas each frame
  update: function(dt) {
    // no need to determine how many pixels you want to
    // move every second and multiple by dt
    // sprite.x += 180 * dt;

    // instead just update by how many pixels you want
    // to move every frame and the loop will ensure 60FPS
    sprite.x += 3;
  },
  render: function() {
    kontra.context.clearRect(0, 0, kontra.canvas.width, kontra.canvas.height);

    sprite.render();
  }
});

Table of Contents

kontra.gameLoop​.isStopped

{boolean}

If the game loop is currently stopped.

let loop = kontra.gameLoop({ /* ... */ });
console.log(loop.isStopped);  //=> true

loop.start();
console.log(loop.isStopped);  //=> false

loop.stop();
console.log(loop.isStopped);  //=> true

kontra.gameLoop​.render()

Called every frame to render the game. Put all of your games render logic here.

kontra.gameLoop​.start()

Start the game loop.

kontra.gameLoop​.stop()

Stop the game loop.

kontra.gameLoop​.update(dt)

dt {number}
The fixed dt time of 1/60 of a frame.

Called every frame to update the game. Put all of your games update logic here.