Gamedev Phaser Content Kit

Article 01: Initialize the framework

Before we can start writing the game's functionality, we need to create a basic structure to render the game inside. This can be done using HTML - Phaser framework will generate the Canvas element on its own.

The game's HTML

The HTML document structure is quite simple, as the game will be rendered entirely on the Canvas element generated by the framework. Using your favourite text editor, create a new HTML document, save it as index.html, in a sensible location, and add the following code to it:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Gamedev Phaser Workshop - lesson 01: Initialize the framework</title>
    <style>* { padding: 0; margin: 0; }</style>
    <script src="js/phaser.2.4.2.min.js"></script>
</head>
<body>
<script>
var game = new Phaser.Game(480, 320, Phaser.AUTO, null, {
    preload: preload, create: create, update: update
});
function preload() {}
function create() {}
function update() {}
</script>
</body>
</html>

We have a charset defined, <title> and some basic CSS in the header resetting the default margin and padding. There is also the <script> element including the Phaser's source code. The body also contains the <script> element, but we will render the game there and write the JavaScript code that controls it.

The Canvas element is generated automatically by the framework. We are initializing it by creating a new Phaser.Game object and assigning it to the game variable. The following parameters are: width and height of the Canvas, rendering method, id of the Canvas if it exist already and the names of the key functions. All the JavaScript code we will write in this tutorial will go between the opening <script> and closing </script> tags.

Our Canvas will be 480 pixels high and 320 pixels wide. Using Phaser.AUTO we are setting up an automatic way to render the game - the other two options are CANVAS and WEBGL. We can set one of them explicitly or use AUTO to let Phaser decide which one to use. It usually works in a way that if the WebGL context is available, the framework will use it, and fall back to Canvas 2D context if it's not available.

We don't have the Canvas element created on our own, so we don't have to enter any reference id and leave it blank as null. The last object contains the three key function names reserved for Phaser - we will use the same names to keep it clean. The preload function takes care of preloading the assets, create is executed once when everything is loaded and ready, and the update function is executed on every frame. These three are enough to make the proper mechanism of loading, starting and updating our game loop.

Compare your code

Here's the full source code of the first lesson, running live in a JSFiddle:

Next steps

Now we've set up the basic HTML and learned a bit about Phaser initialization, so let's continue to the second lesson and see how scaling work.