Development Guide: Web Games using JavaScript

Game development is an alluring subject to study. Part of the reason is that, at least once in our life, while we play games—be they 2D or 3D—either we want to make games we like with some amendments, or, admit it, we deem to create a hack for a certain game. In either case, we must know the basics of game development as the first step towards achieving our goal. In this article, we will focus at the mechanics of a 2D web-game using JavaScript, which you can run on any browser. Without further ado, let’s get started!

Prerequisites

In this section, I will discuss the things that are required to develop the game.

Tools

  • Google Chrome or Safari (Any browser you like; I am going to use Safari in the article.)
  • Code Editor (You can use simple Text Editor; however, I am using Visual Studio Code.)
  • Photoshop (for creating Sprites)

Languages

As this article focuses on the web games, the following are the required languages:

  • HTML5 (for scaffolding the webpage)
  • CSS (for prettifying the webpage)
  • JavaScript (ES6+) (for game creation)

Knowledge to have

You are supposed to have some know-how of HTML, CSS and JavaScript programming for this article. If you do not know anything about these languages, then I am afraid, this article will be hard to follow. Although I would try to explain most of the things.

Essential Concepts

Before diving into the coding part, you must have the following essential concepts:

Canvas

In HTML, we define a canvas for our 2D games. The question arises what a canvas is. Well, in simple terms, a canvas is a drawing board where you can draw. That’s it! Now in order to draw, we need to have a specify the kind of drawing board it is. The kind can be specified by using the context of the Canvas. In a 2D world, the context of the Canvas would take the following string as a parameter: “2d”. As we are developing a 2D game using HTML and JavaScript, here is how we can initiate the canvas in HTML:

    <canvas id="canvas" width="500" height="500"></canvas>
  • id is used to access the HTML canvas in JavaScript. Here the value of id is set to canvas.
  • We have to specify the width and height of the canvas. As I mentioned before, imagine the canvas as the drawing board. The drawing board must have some width and height. Here in the case, I have specified the following values: width = 500, and height = 500.

Now that we have initiated the Canvas in HTML, it is time to access it in JavaScript.

>   let canvas = document.getElementById("canvas");

In the above line of code, document refers to the whole webpage. Now in order to get any HTML element by its id, we use the following helper function: getElementById. It take only one parameter, which is the value of the id that you have specified in the HTML document. As you can see above that the id of the canvas is canvas. You can specify the value of id whatever you like.

Now that we have the drawing board, it is time to define what kind of board it is. Therefore, for that, we need to use the context of the canvas. In order to get the context of the canvas, we would use getContext function of the canvas object as follows:

let context = canvas.getContext("2d");

As you can see in the previous line of code that we have specified “2d” as the parameter of the getContext (for the development of the 2d game).

Draw Rectangle in Canvas

For learning purpose, let us draw a rectangle in the case! For drawing anything, we would use the context of the canvas as follows:

context.rect(0,0,500,500);

context has the helper function rect that takes the following parameters (in order):

  • x: The starting x-coordinate of a rectangle.
  • y: The starting y-coordinate of a rectangle.
  • width: Width of a rectangle.
  • height: Height of a rectangle.

As we have defined the canvas to be 500x500, we have drawn the rectangle with the same dimensions. However, the question here arises: what is the coordinate system of the canvas?

Coordinate System

The following is the coordinate system of the canvas:

1.gif

  • The upper left corner is the origin of the canvas.
  • The positive x-axis is towards the east with respect to the origin.
  • The positive y-axis is towards the south with respect to the origin.

Color the rectangle

Now in order to fill the rectangle with the specific colour, we need to specify the fillStyle of the context, which is as follows:

context.fillStyle = "darkgreen";

In the above line of code, the fillStyle is set to a darkgreen colour.

After specifying the fillStyle, fill the rectangle by using the following line of code:

context.fill();

Now if you refresh the page, you would see the canvas filled with the dark-green colour as shown below:

2.png

Draw Sprite (or Image)

In this article, we are going to use the cards sprite named as cardsprite (as shown below).

cardsprite.png

Draw Whole Image

In order to draw the whole image, we first need to initiate the image using the Image class and set the source by using the property called src. The source code to draw the complete image into canvas is as follows:

let cardsprite = new Image();
cardsprite.src = "cardsprite.png"

function draw() {
    let width = cardsprite.width;
    let height = cardsprite.height;
    canvas.width = width;
    canvas.height = height;
    context.clearRect(0,0,width,height);
    context.drawImage(cardsprite, 0, 0, width,height);
}

setInterval(draw, 100);
  • The cardsprite is initiated with the Image class.
  • The source is set to the image location. In this case, the png file is located where there is this javascript file.
  • draw function is created; in that function, first the width and the height of the cardsprite is saved in the temporary variables and then the canvas size is resized to the cardsprite width and height (you may resize the image, but that is not the scope of this article).
  • Then we clear the canvas by using the clearRect function. The reason is that we are drawing this image every 100ms (as setInterval’s time is set to 100ms). It means that if we do not clear the canvas, the image will continuously be drawn on the previous images.
  • At the end we used drawImage function, which takes the following parameters: the first parameter is the image object, the second parameter is the starting x-position on the canvas, the third parameter is the starting y-position on the canvas, the fourth parameter is the width of the image, and the last parameter is the height of the image.
  • Once you refresh the page, you would see the cardsprite on the browser page.

Animation (BONUS)

In this section, I am going to share the code for the animation of the sprite; in future articles, I shall dive deep into the animation section for 2D games. The code for animation (JavaScript file) is as follows:

let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");

let cardsprite = new Image();
cardsprite.src = "cardsprite.png"

let width;
let height;
let singleCardWidth;
let singleCardHeight;
let xframe = 0;
let yframe = 0;
function draw() {
    width = cardsprite.width;
    height = cardsprite.height;
    context.clearRect(0,0,width,height);
    canvas.width = width;
    canvas.height = height;

    singleCardWidth = Math.floor(width/13);
    singleCardHeight = Math.floor(height/4)

    context.fillStyle = "darkgreen";
    context.rect(0,0,width,height);
    context.fill();

    context.drawImage(cardsprite, 
                      0 + (xframe*singleCardWidth), 
                      0 + (yframe*singleCardHeight), 
                      singleCardWidth,
                      singleCardHeight,
                      width/2 - singleCardWidth,
                      height/2 - singleCardHeight,
                      singleCardWidth,
                      singleCardHeight
    );

    xframe++;
    if (xframe > 12) {
        xframe = 0;
        yframe++;
    }

    if (yframe > 3) {
        yframe = 0;
    }
}

setInterval(draw, 200);

Output (GIF)

webgames_israr.gif

Summary

In this article, we have learnt the mechanics of the web 2D games using the pure JavaScript. The animation logic is also shared in this article. In the future articles, we will explore the world of web gaming more. For now, I am saying goodbye… till we meet again! 😊

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?