× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

HTML5 Canvas: Moving a character with Sprites

See in this article how to work with the HTML5 Canvas and see how to move a character using Sprites.

We know that with the rise of HTML5 and CSS and Javascript advance became possible to develop full games basically using Web standards. This does not indicate that already consolidated platforms like Flash and XNA will fall into disuse, at least not now, but it meant a breakthrough for enthusiasts of game development for the web that started to become less dependent on other technologies.

As with any game that uses "chars" (characters), one of the first steps is to draw and move a "puppet". Initially it is customary to practice with fixed shape objects (circle, rectangle, etc...) And then goes to use objects in different ways. In this category come the various characters in the game, which has changed its shape during displacement (to give an idea of movement of legs, arms, etc…).

Some engines have more powerful features to make this move in practice, providing and using models (mostly 3D), whose movements are defined in a modeling job character. But in simpler engines (mainly 2D), the most used to design and operate these characters is using SPRITES, a technique that will be explained later.

In this article we will see how to use this technique with the CANVAS tag in HTML5 and Javascript language assistance to move a character in html page.

Note: here we will implement the movement in only one direction (to the right), which will be controlled by the arrow keys. The reader who is interested can use the same technique to develop the other movements and increase the sample as needed.


Sprites, as they are called, are images containing various forms / positions of one or more objects. For example, a sprite for a given character must have "scenes", moving their positions. For example, he stopped, stepping with the right leg, stepping with the left leg, etc…

The following figure shows the sprite that was used in this article, image obtained on the internet.

Sprite used

Figure 1: Sprite used

As we see, the image stores several times the displacement of a guy going right.

The technique of using sprites to give the impression of movement is to cut parts of the image and draw them in the area reserved for this purpose in sequence. For this, the dimensions of each piece must be well defined and known by the programmer that can divide the original image into several parts and use only that regarding the current position.

Since the goal of this article is not to explain how crop images using Javascript, otherwise we will use a bit less practical, but it also works and results in the same effect.

What we will do is crop the pictures beforehand using any image editor, saving each position in a separate file. It is important that all parties have the same size and the character is positioned in the same way in all of them. In this case, we use pictures and dimensions 200x340px we position at the bottom left of the frame. Then will save each image with a number indicating the position in displacement, with 0 (zero) where the first character is stopped. We will then have the images 0.png, 1.png until 6.png.


The HTML code used is quite simple and basically consists of a tag CANVAS (beyond the basic structure of the page) and reference to a Javascript file that develop later.

Listing 1: HTML code of the page

<!DOCTYPE html>
    <meta charset="UTF-8" />
    <title>Canvas Tutorial</title>
        <canvas id="canvas" width="1000" height="340" style="background:rgb(233,233,233)">
If you see this text is because your browser do not support the canvas tag.
    <script type="text/javascript" src="desenhar_personagem.js"></script>

The reference was made to the script after the canvas tag to ensure that the canvas is already loaded (or not) when the script is interpreted.

We use the color RGB (233, 233, 233) to be the same as the background image we take as an example.

We then proceeded to the main part of the code, Javascript script that "gives life" to the character.

The Javascript code

Following are the various snippets desenhar_personagem.js file, which should be saved in the same directory as the html and images, to facilitate the understanding and use. The code is presented in a logical order, so as a suggestion is to insert them in the file in the sequence they appear here.

Listing 2: Declaration of variables

var canvas;/ / the canvas element which will draw on
var ctx;/ / the "context" of the canvas that will be used (2D or 3D)
var dx = 50;/ / the rate of change (speed) horizontal object
var x = 30;/ / horizontal position of the object (with initial value)
var y = 0;/ / vertical position of the object (with initial value)
var WIDTH = 1000;/ / width of the rectangular area
var HEIGHT = 340;/ / height of the rectangular area
var tile1 = new Image ();/ / Image to be loaded and drawn on canvas
var posicao = 0;/ / display the current position of the character
var NUM_POSICOES = 6;/ / Number of images that make up the movement

All lines of the listing above are commented, explaining each variable declared, and then dispenses more details.

Listing 3: Function KeyDown

	function KeyDown(evt){
    switch (evt.keyCode) {
        case 39:  /* Arrow to the right */
            if (x + dx < WIDTH){
                x += dx;
                if(posicao == NUM_POSICOES)
                    posicao = 1;

This function will be used to handle the event Key Down page. As stated earlier, only the arrow to the right was used to move the character on the screen.

First check to see if the movement is within the reserved area, if we increase the variables that indicate the horizontal position and the state of "puppet". If the state of the character is the last of the sequence of images, we return to the initial state, thus maintaining a cyclical movement.

Listing 4: Draw Function

	function Draw() {    
    tile1.src = posicao+".png";
    ctx.drawImage(tile1, x, y);

In this function we use the variable that indicates the position / status of the character and use to load its image (0, 1, 2 ...). Then, with the drawImage function object ctx, draw the picture in the reserved area in coordinates x and y.

Listing 5: Function LimparTela

	function LimparTela() {
    ctx.fillStyle = "rgb(233,233,233)";    
    ctx.rect(0, 0, WIDTH, HEIGHT);

The function LimparTela, as the name suggests, is used to clean the "buffer", ie redraw the background of the rectangular area so that we can again draw the character on it. This function will be used continuously to the screen to be cleaned and repainted, giving the impression of movement.

Listing 6: Function Update

	function Update() {

This function is responsible for executing the design process, and calling functions LimparTela and Draw, in that order. The update function will be invoked repeatedly at intervals defined below.

Listing 7: Start Function

	function Start() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    return setInterval(Update, 100);

In Listing 7 we have the Start function, responsible for instantiating objects used throughout the code and set the continuous call to the function Update. Using the setInterval function, we make the update is invoked every 100 milliseconds, making the screen is kept current.

In real situations, this range is much smaller, in the range of 10 or even 1 millisecond.

Listing 8: Starting code execution

	window.addEventListener('keydown', KeyDown);

The first line of code listing above causes the previously defined function KeyDown be added as "event handler" event keydown the window.

Then call the Start function, as seen above, starts the whole process.

Having saved html and js files along with the images, and opening the document in the browser, we have the following result.

Character drawn in motion

Figure 2: Character drawn in motion

It is possible that there small "delays" in the design and some updates visible image, it is corrected with buffer techniques applied much in game development, but will not be presented here.


The aim of this article was to present a way to draw and move a character on the screen, using the HTML5 CANVAS tag with the help of Javascript.

Microsoft MVP, Bachelor in Science And Technology, Editor and Consultant at DevMedia with more than 7 years of experience in software development.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login