Gamedev Phaser Content Kit

Article 03: Load the assets and print them on screen

Our game's idea is to have the ball rolling on the screen bouncing off the paddle, hitting the bricks and collecting the points. Let's start with creating the JavaScript variable for the ball - add it between the game initialization and the preload function:

var game = new Phaser.Game(480, 320, Phaser.AUTO, null, {
    preload: preload, create: create, update: update
});

var ball;

function preload() {
    game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
    game.scale.pageAlignHorizontally = true;
    game.scale.pageAlignVertically = true;
    game.stage.backgroundColor = '#eee';
}
function create() {
}
function update() {
}

Note: for the sake of this tutorial we will use global variables. The purpose of the tutorial is to teach Phaser-specific approach to game development and don't enforce any of the available code style guides which are subjective to preferences of every single developer.

Loading and printing the images on our Canvas is a lot easier using Phaser than doing that in pure JavaScript. To load the asset, we will use the game object created by Phaser and execute the load.image method inside the preload function:

function preload() {
    // ...
    game.load.image('ball', 'img/ball.png');
}

The first parameter is the name of the asset we want to have - it will be used across our game, so it would be great to give it a proper meaning. The second parameter is the relative path to the graphic asset. In our case we will load the image of the blue ball that will be used later in the game to destroy blocks and earn points.

Now, to show it on the screen we will use another Phaser method called add.sprite in the create function:

function create() {
    ball = game.add.sprite(50, 50, 'ball');
}

It will add the ball and render it on the screen. The first two parameters are the top and left positions on the screen and the third one is the name of the asset we defined earlier. That's it - if you launch the index.html file you will see the image already loaded and rendered on Canvas!

Ball on the screen

Compare your code

You can check the finished code for this lesson for yourself in the live demo below, and play with it to understand better how it works:

Next steps

Printing out the ball was easy, so let's try to move the ball on screen.