Getting Started
Download
- Production and development versions
$ npm install kontra
Load
Load the library by adding it as a script tag on the page.
<script src="kontra.js"></script>
Kontra also supports ES modules and exports all API functions, allowing you to import it into your code as well. This is the recommended way to create custom builds of the library.
import { Sprite } from 'kontra';
Want to get started without all the hassle? Web Maker has you covered! When you start a new project, select the Kontra Game Engine from the list of predefined templates and you're good to go. Learn more by reading the Web Maker and JS13k tutorial.
Initialize
Initialize the game by calling init() to create the drawing context. By default, it will use the first canvas element on the page, but you can also pass it the ID of the canvas or a Canvas element.
The init() function returns the canvas and context used for the game.
import { init } from 'kontra';
let { canvas, context } = init();
Create
After the game is initialize, you can create a simple Sprite and Game Loop in just a few lines of code
import { init, Sprite, GameLoop } from 'kontra';
let { canvas } = init();
let sprite = Sprite({
x: 100, // starting x,y position of the sprite
y: 80,
color: 'red', // fill color of the sprite rectangle
width: 20, // width and height of the sprite rectangle
height: 40,
dx: 2 // move the sprite 2px to the right every frame
});
let loop = GameLoop({ // create the main game loop
update: function() { // update the game state
sprite.update();
// wrap the sprites position when it reaches
// the edge of the screen
if (sprite.x > canvas.width) {
sprite.x = -sprite.width;
}
},
render: function() { // render the game state
sprite.render();
}
});
loop.start(); // start the game