Create simple HTML5 canvas “game” using pure JavaScript

I have always been interested in games. Now that I’m learning JavaScript programming, I decided to make a simple “game” in HTML5 canvas element. Disclaimer: this is my first tutorial on building a game in JavaScript so there might be some bugs and mistakes.

The final result: (move with WASD keys)


Download necessary resources

Firstly, you will need two images: one of a grass:

and the second one of a ball:

You can, of course, substitute them with your own images.

Create simple website with canvas

Now we need to create a simple HTML website with a canvas element. It might look like this:

<!DOCTYPE html>
    <title>Tank Game</title>

    <canvas id="main_canvas" height="300" width="400"></canvas>


I made the canvas 300 pixels tall and 400 pixels wide. Save the page as ‘game.html’ in some folder.

The next step is to program the actual JS code.

Building game code

I’ve divided the game into two JavaScript files, just to show you how you can create an object (in our case the ball) and the game controls separately. Add following lines under the canvas element in our simple page.


Now, create a blank new file called ‘ball.js’ in the same folder where the ‘game.html’ was created. The content of our script is:

(function(window){ // pass window property to an anonymous function

    // object Ball has 3 parameters - ctx is the context of the canvas
    // x,y are the starting positions of the Ball
    function Ball(ctx, x, y) {
        this.ctx = ctx;
        this.x = x;
        this.y = y;
        this.speed = 60; // set the speed of the ball

        this.model = new Image(); // model is the image of the ball
        this.model.src = "ball.png"; // set the path to the image of the ball

    Ball.prototype.draw = function() { // function draw draws the ball
            this.ctx.drawImage(this.model, this.x, this.y);

    window.Ball = Ball; // register Ball property in the global namespace


I hope the comments explain the code. The Ball object will be our ball that can be moved in the canvas.

Now, the harder part. Create new file called ‘game.js’ in the same folder as the other files. It will be the main game loop and controls. Here’s the code:

(function () { // make an anonymous function so we don't pollute the global namespace
    var canvas; // our canvas
    var ctx; // canvas context
    var ball; // our ball object
    var keysDown = {}; // for keyboard handling
    var bgImage, bgReady = false; // background image
    var then; // used for game loop

    function init() { // prepares the canvas and initializes the game
        canvas = document.getElementById("main_canvas"); // get the canvas
        ctx = canvas.getContext('2d'); // create canvas Context

        bgImage = new Image(); // background image, grass in our case
        bgImage.onload = function() { // if the image is ready...
            bgReady = true;
            ctx.drawImage(bgImage, 0, 0); // draw it
        bgImage.src = "grass.jpg"; // the path to the background image

        // register event listeners for keyDown and keyUp
        window.addEventListener("keydown", function(e) {
            keysDown[e.keyCode] = true; // key with keyCode is pressed, so we set it to true
        }, false);
        window.addEventListener("keyup", function(e) {
            delete keysDown[e.keyCode]; // when we release the key, it is removed from the pressed keys object
        }, false);

        ball = new Ball(ctx, canvas.width / 2, canvas.height / 2); // let's put the ball in the middle of the canvas
        then = Date.now();
        setInterval(mainLoop, 1); // set the main game loop

    // called each iteration of the game loop
    function update(modifier) {

        // keypress handling
        if (38 in keysDown)  //up movement - W
           ball.y -= ball.speed * modifier;
        if (40 in keysDown) //down movement - S
            ball.y += ball.speed * modifier;
        if (37 in keysDown) //left movement - A
            ball.x -= ball.speed * modifier;
        if (39 in keysDown) //right movement - D
            ball.x += ball.speed * modifier;

        // if the ball runs out of the canvas, let's put it on the other side of it
        if (ball.x < 0)
            ball.x = canvas.width;
        if (ball.x > canvas.width)
            ball.x = 0;
        if (ball.y < 0)
            ball.y = canvas.height;
        if (ball.y > canvas.height)
            ball.y = 0;

    function draw() {
            ctx.drawImage(bgImage, 0, 0); // draws the background
            ball.draw(); // draws the ball

    // main game loop
    function mainLoop() {
        var now = Date.now();
        var delta = now - then;

        update(delta / 1000); // update movement
        draw(); // draw the whole canvas

        then = now;

    init(); // call the initialization function


The code should explain itself. Save all of the files and open ‘game.html’ in your favorite browser. The game should run🙂 I’ve tested it only in Google Chrome.

I hope you like the tutorial. Have a nice day.

One thought on “Create simple HTML5 canvas “game” using pure JavaScript

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s