How To Make HTML5 Game in pure JavaScript

HTML5 01 Mar 2019 Administrator
How to make your own HTML5 game in pure javascript

Note: This is a start point for BEGINNERS and does not give you a ready-made html game.
In this tutorial we create a very simple HTML5 game written entirely in pure JavaScript and rendered on HTML5 Canvas.

You will learn the basics of using the Canvas element to implement fundamental game mechanics like rendering and moving objects on html canvas and control machanisms.
After that, you can pick any framework you like and use it for your projects. Frameworks speed up development time and help take care of boring parts of the game.
About the best Javascript Frameworks for building HTML5 Games we will write in other post, so check our blog regularly.

Tutorial: How to make your own HTML5 Game

Assuming you have basic knowledge in html and javascript, let's start:

1. HTML5 Canvas element and drawing on it

The HTML document structure is quite simple, as the game will be rendered entirely on the <canvas> element. Using your favourite text editor, create a new HTML document, save it as index.html and add the following code to it:

<!DOCTYPE html>
<html>
 <head>
 
  <style>
    canvas {
        border:1px solid #d3d3d3;
        background-color: #f1f1f1;

    }

 
</style>

 </head>

 <body>

    <canvas id="myCanvas" width="800" height="480"/>

    <script>
      //Our game logic goes here
   
</script>
 </body>

</html>

The body contains <canvas> and <script> elements — we will render the game inside the <canvas> and write the JavaScript code that controls the game in the <script> tag. The <canvas> element has an id of myCanvas to allow us to easily grab a reference to it.

Drawing on HTML Canvas

To be able to render graphics on the <canvas> element, first we have to grab a reference to it in JavaScript. Add the following code inside your <script>  </script> tag.

var myGameCanvas = {
  canvas: document.getElementById("myCanvasElement"),

  start: function() {
        this.context = this.canvas.getContext("2d");
        this.interval = setInterval(updateGameCanvas, 10);
  },

  stop: function() {
       clearInterval(this.interval);
  },

  clear: function() {
       this.context.clearRect(0, 0, this.canvas.width,      this.canvas.height);
  }
};

Here we make the object myGameCanvas which has some methods and properties required further in our game.

The myGameCanvas.canvas property is a reference to our <canvas> element, the main element of our game. Here we draw all game components.

The myGameCanvas.start() method will get from canvas built-in object, called the getContext("2d") object, with methods and properties for drawing and will keep it in myGameCanvas.context property.

setInterval(updateGameCanvas, 10);

The setInterval() method calls a function at specified intervals (in milliseconds). This method will continue calling the function until clearInterval() is called, or the window is closed. This method we use for our game animations, by updating canvas context every 10 milliseconds. About game loop and animations we'll write in other tutorial.

Next, the myGameCanvas.clear() cleans the canvas context and prepares it for a new drawing.

Now I've prepared the canvas for drawing, it's time to draw something on it. In any game there are many objects, some static other dynamic, and one of them represent the player. Let's create our player object, add the following code inside your <script> </script> tag.

function playerObject(width, height, color, x, y) {
    this.width = width;
    this.height = height;
    this.speed = 0;
    this.angle = 0;
    this.moveAngle = 0;
    this.x = x;
    this.y = y;

  this.draw = function() {
    ctx = myGameCanvas.context;
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.rotate(this.angle);
    ctx.fillStyle = color;
    ctx.fillRect(this.width / -2, this.height / -2, this.width,     this.height);
    ctx.restore();
  };

  this.update = function() {
     this.angle += this.moveAngle * Math.PI / 180;
     this.x += this.speed * Math.sin(this.angle);
     this.y -= this.speed * Math.cos(this.angle);
  };
}

We just created an object with some basic properties, like dimensios (width, height), speed, angle and coordinates. More interesting here we have 2 methods draw() and update().

The draw() method drawing a rectange with ctx.fillRect() on canvas context ctx = myGameCanvas.context; color it with ctx.fillStyle = color; places it on x,y coordinates with ctx.translate(this.x, this.y);

The update() method helps to move and rotate our playerObject on the canvas.
Detailed information about HTML5 Canvas and about it's properties you can find in our dedicated post about html canvas.

2. Game Loop and JavaScript Animation

Until now we created the game area and our main player object, but, for animating our objects in a game we need an animation cycle, something that will help us make our objects dynamic. Yes, we already did this in the myGameCanvas.start() method by calling a function every 10 milliseconds, so, let's declare a function that will redraw our canvas every 10 ms. Add code bellow in <script> </script> tag in your html file:

function updateGameCanvas() {
     myGameCanvas.clear();    // prepare canvas for next draw
     myEnemy.moveAngle = 0;   // reset playerObject rotation
     myEnemy.speed = 0;       // reset playerObject speed
     keyboardControl();       // check keyboard input events
     myEnemy.update();        // update playerObject properties
     myEnemy.draw();          // draw new playerObject
}

This function is executed every frame (10ms) and will clear canvas and draw playerObject again and again until clearInterval() is called, or window is closed. By changing playerObject propeties (angle, speed, coordinates) we make a clean animation.
This method using setInterval() is the simplest Javascript method for game loop or canvas animation. There are other ways, more complicated and more efficient, but to understand the process, we started from the simplest one.

3. Game Controls and Keyboard Events

If we combine all of the above code, the result will be static, no animation/movement on the our html page, even if the canvas will update each frame. This because the playerObject has the same properties in each frame and he still stands.

To make it move, we need to change its rotation and / or positioning properties. For this we will use the keyboard, or more precisely some keys that our game will listen to. First we add EventListeners in our game, listeners for keyboar inputs.

window.addEventListener('keydown', function (e) {
    e.preventDefault();
    myGameCanvas.keys = (myGameCanvas.keys || []);
    myGameCanvas.keys[e.keyCode] = (e.type == "keydown");
});

window.addEventListener('keyup', function (e) { 
    myGameCanvas.keys[e.keyCode] = (e.type == "keydown");
});

This piece of javascript code listening for keydown & keyup events and store keys codes in myGameCanvas.keys object, this object is used in next function for changing playerObject properties.

function keyboardControl(){
    if (myGameCanvas.keys && myGameCanvas.keys[37]) {
        myEnemy.moveAngle = -enemySpeed;
    }

    if (myGameCanvas.keys && myGameCanvas.keys[39]) {
        myEnemy.moveAngle = enemySpeed;
    }

    if (myGameCanvas.keys && myGameCanvas.keys[38]) {
        myEnemy.speed= enemySpeed;
    }

    if (myGameCanvas.keys && myGameCanvas.keys[40]) {
        myEnemy.speed= -enemySpeed;
    }
}

4. Put it all together and Finish

So, the basic and the simplest HTML5 game setup we did. We have a canvas, an object on it, an animation mechanism and an input events listeners. But, finishing our game we have to create our game objects on window load. For that we make and call a function that create our objects in the page. Add the following before </script> tag.

var myEnemy;  // global reference to our playerObject
var enemySpeed = 2;  // speed of playerObject

function startGame() {
     myEnemy = new playerObject(30, 30, "red", 225, 225);
     myGameCanvas.start();
}

startGame(); // start Game on window load

Put all together, save your index.html file, open it and check the results. Use arrow keys for moving/rotate your player.

All rights reserved © 2019 ONEBOX Games.