Browser Games | Cybiko | Amiga | Applications | Windows Games | Python | Guides | Site Map

HTML5 Canvas Example - A Bouncing Block

This basic example shows how to create a web page with a canvas and how to move an image (in this case a block) inside it. Most of it is self explanatory so we will not be going into too much depth.

The Web Page

Below is a simple page, the most important parts are:

<!DOCTYPE html>
<script type="text/javascript" src="block.js"></script>
<body onload="init();">
<canvas id="canvas" width="480" height="480">Canvas tag not supported..</canvas>

The above should be copied and saved as 'block.htm'.

The Javascript Program

Now we have our page, we need to add a block and move it! The code parts should be saved in a file called 'block.js'. Here's how it works:

This is just boiler plate stuff, we put the browser into strict mode, this is better for tracking errors and preventing bugs from entering our code. Always use it!

We then create variables that will be used to later manipulate our canvas and our block image. The last line creates an 'associative array' to hold the position and direction of our block. The variable 'ctx' hold the Canvas 'context', this points to the Canvas methods and properties.

"use strict";

var ctx;
var canvas;
var img=new Image();
var pos={x:0, y:0, xdir:2, ydir:2};

The init() function fills in the canvas details and sets up the default position of the block. Once the image has loaded, the update() function is called 25 times a second to update our block.

Note : You will to change the image path if your image is in a different location. If you need a block image, right click on this and save : block.gif

function init()
	ctx = canvas.getContext('2d');
	img.onload= function(){
		setInterval(update, 1000/25);
	img.src = 'gfx/block.gif';	

The update() function simply calls the move and draw functions...

function update()

The move() function updates the block position, it touches or crosses one of the edges then the direction is flipped so that it moves in the opposite direction.

function move()
	if (pos.x<=0 || (pos.x+32)>canvas.width){pos.xdir*=-1;}
	if (pos.y<=0 || (pos.y+32)>canvas.height){pos.ydir*=-1;}

The draw() function clears the canvas and draws our block!

function draw()
	ctx.fillStyle = "white";


All being well, you should end up with something like this:

This requires a browser that supports HTML5 / Canvas such as Mozilla Firefox 11, Apple Safari 5, Opera 11 or Google Chrome


Support this site : Visit Play-Asia for games and accessories for new and classic games consoles!