HTML5 Zone is brought to you in partnership with:

David Catuhe is a Microsoft HTML5 Evangelist based in Paris, France. He does much of his research on Windows 8, Kinect, and the various HTML5 standards and JS libraries. David is a DZone MVB and is not an employee of DZone and has posted 26 posts at DZone. You can read more from them at their website. View Full User Profile

How to write a BrikBloc game with HTML5 SVG and Canvas

10.25.2011
| 10291 views |
  • submit to reddit

This tutorial is a great instructional walkthrough that will strenghthen your skills in HTML5 Canvas and SVG development by creating a real-world web-based game.  The starter and full solution pack can be found here.

Summary Description: image

  1. Introduction
  2. Prerequisites
  3. Setting up the background
  4. Setting up the game
  5. Conclusion

Introduction

The goal of this tutorial is discovering graphics development using SVG and Canvas (which are two majors technologies of HTML5).

To do so, we will write together a brick breaker game (à la Arkanoïd or Blockout). It will be composed of an animated background (using Canvas) and will use SVG for bricks, pad and ball.

You can try the final version here: http://www.catuhe.com/ms/en/index.htm

Prerequisites

Setting up the background

The background is only an alibi to use a canvas. It will allow us to draw pixels in a given area. So we will use it to draw a space wormhole (yes, I love Stargate!). Users will have choice to display it or not using the mode button:

Description: image

You can note that we will add a performance counter in the right top corner (just to see the power of accelerated graphics)

Setting up HTML5 page

Starting from the index.htm file, we will add our canvas as child of the div "gameZone":

<canvas id="backgroundCanvas">
    Your browser doesn't support HTML5. Please install Internet Explorer 9 :
    <br />
    <a href="http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie9_bow_Bing&WT.srch=1&mtag=SearBing">
        http://windows.microsoft.com/en-US/internet-explorer/products/ie/home?ocid=ie9_bow_Bing&WT.srch=1&mtag=SearBing</a>
</canvas>

Adding JavaScript code

The background is handled by background.js file (what a surprise!). So we have to register it inside index.htm. So just before the body closing tag, we will add the following code:

<script type="text/javascript" src="background.js"></script>

Setting up constants

First of all, we need constants to drive the rendering:

var circlesCount = 100; // Circles count used by the wormhole
var offsetX = 70; // Wormhole center offset (X)
var offsetY = 40; // Wormhole center offset (Y)
var maxDepth = 1.5; // Maximal distance for a circle
var circleDiameter = 10.0; // Circle diameter
var depthSpeed = 0.001; // Circle speed
var angleSpeed = 0.05; // Circle angular rotation speed

You can of course modify these constants if you want different effects on your wormhole.

Getting elements

We also need to keep reference to main elements of the html page:

var canvas = document.getElementById("backgroundCanvas");
var context = canvas.getContext("2d");
var stats = document.getElementById("stats");

How to display a circle?

The wormhole is only a sequence of circles with different positions and sizes. So to draw it, we will use a circle function which is build around a depth, an angle and an intensity (the base color).

 

function Circle(initialDepth, initialAngle, intensity) {
}

The angle and the intensity are private but the depth is public to allow the wormhole to change it.

function Circle(initialDepth, initialAngle, intensity) {
var angle = initialAngle;
this.depth = initialDepth;
var color = intensity;
}

We also need a public draw function to draw the circle and update depth, angle. So we need to define where to display the circle. To do so, two variables (x and y) are defined:

var x = offsetX * Math.cos(angle);
var y = offsetY * Math.sin(angle);

As x and y are in space coordinates, we need to project them into the screen:

function perspective(fov, aspectRatio, x, y) {
    var yScale = Math.pow(Math.tan(fov / 2.0), -1);
    var xScale = yScale / aspectRatio;
 
    var M11 = xScale;
    var M22 = yScale;
 
    var outx = x * M11 + canvas.width / 2.0;
    var outy = y * M22 + canvas.height / 2.0;
 
    return { x: outx, y: outy };
}

So final position of the circle is computed by the following code:

var x = offsetX * Math.cos(angle);
var y = offsetY * Math.sin(angle);
var project = perspective(0.9, canvas.width / canvas.height, x, y);
var diameter = circleDiameter / this.depth;
var ploX = project.x - diameter / 2.0;
var ploY = project.y - diameter / 2.0;

And using this position, we can simply draw our circle:

context.beginPath();
context.arc(ploX, ploY, diameter, 0, 2 * Math.PI, false);
context.closePath();
var opacity = 1.0 - this.depth / maxDepth;
context.strokeStyle = "rgba(" + color + "," + color + "," + color + "," + opacity + ")";
context.lineWidth = 4;
context.stroke();

You can note that the circle is more opaque when it is closer.

So finally:

function Circle(initialDepth, initialAngle, intensity) {
    var angle = initialAngle;
    this.depth = initialDepth;
    var color = intensity;
 
    this.draw = function () {
        var x = offsetX * Math.cos(angle);
        var y = offsetY * Math.sin(angle);
 
        var project = perspective(0.9, canvas.width / canvas.height, x, y);
        var diameter = circleDiameter / this.depth;
 
        var ploX = project.x - diameter / 2.0;
        var ploY = project.y - diameter / 2.0;
 
        context.beginPath();
        context.arc(ploX, ploY, diameter, 0, 2 * Math.PI, false);
        context.closePath();
 
        var opacity = 1.0 - this.depth / maxDepth;
        context.strokeStyle = "rgba(" + color + "," + color + "," + color + "," + opacity + ")";
        context.lineWidth = 4;
 
        context.stroke();
 
        this.depth -= depthSpeed;
        angle += angleSpeed;
 
        if (this.depth < 0) {
            this.depth = maxDepth + this.depth;
        }
    };
};

Initialization

With our circle function, we can have an array of circles that we will initiate more and more close to us with a slight shift of the angle each time:

// Initialization
var circles = [];
var angle = Math.random() * Math.PI * 2.0;
var depth = maxDepth;
var depthStep = maxDepth / circlesCount;
var angleStep = (Math.PI * 2.0) / circlesCount;
for (var index = 0; index < circlesCount; index++) {
circles[index] = new Circle(depth, angle, index % 5 == 0 ? 200 : 255);
depth -= depthStep;
angle -= angleStep;
}

Computing FPS

We can compute FPS by measuring the amount of time between two calls to a given function. In our case, the function will be computeFPS. It will save the last 60 measures and will compute an average to produce the desired result:

// FPS
var previous = [];
function computeFPS() {
if (previous.length > 60) {
previous.splice(0, 1);
}
var start = (new Date).getTime();
previous.push(start);
var sum = 0;
for (var id = 0; id < previous.length - 1; id++) {
sum += previous[id + 1] - previous[id];
}
var diff = 1000.0 / (sum / previous.length);
stats.innerHTML = diff.toFixed() + " fps";
}

Drawing and animations

The canvas is a direct mode tool. This means that we have to reproduce all the content of the canvas every time we need to change something.

And first of all, we need to clear the content before each frame. The better solution to do that is to use clearRect:

// Drawing & Animation
function clearCanvas() {
    context.clearRect(0, 0, canvas.width, canvas.height);
}

So the full wormhole drawing code will look like:

function wormHole() {
    computeFPS();
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight - 130 - 40;
    clearCanvas();
    for (var index = 0; index < circlesCount; index++) {
        circles[index].draw();
    }
 
    circles.sort(function (a, b) {
        if (a.depth > b.depth)
            return -1;
        if (a.depth < b.depth)
            return 1;
        return 0;
    });
}

The sort code is used to prevent circles from overlapping.

Setting up mode button

To finalize our background, we just need to hook up the mode button to display or hide the background:

var wormHoleIntervalID = -1;
 
function startWormHole() {
    if (wormHoleIntervalID > -1)
        clearInterval(wormHoleIntervalID);
 
    wormHoleIntervalID = setInterval(wormHole, 16);
 
    document.getElementById("wormHole").onclick = stopWormHole;
    document.getElementById("wormHole").innerHTML = "Standard Mode";
}
 
function stopWormHole() {
    if (wormHoleIntervalID > -1)
        clearInterval(wormHoleIntervalID);
 
    clearCanvas();
    document.getElementById("wormHole").onclick = startWormHole;
    document.getElementById("wormHole").innerHTML = "Wormhole Mode";
}
 
stopWormHole();

Setting up the game

In order to simplify a bit the tutorial, the mouse handling code is already done. You can find all you need in the mouse.js file.

Description: image

Adding the game JavaScript file

The background is handled by game.js file. So we have to register it inside index.htm. So right before the body closing tag, we will add the following code:

<script type="text/javascript" src="game.js"></script>

Updating HTML5 page

The game will use SVG (Scalable Vector Graphics) to display the bricks, pad and ball. The SVG is a retained mode tool. So you don't need to redraw all every time you want to move or change an item.

To add a SVG tag in our page, we just have to insert the following code (just after the canvas):

<svg id="svgRoot">
<circle cx="100" cy="100" r="10" id="ball" />
<rect id="pad" height="15px" width="150px" x="200" y="200" rx="10" ry="20"/>
</svg>

As you can note, the SVG starts with two already defined objects : a circle for the ball and a rectangle for the pad.

Defining constants and variables

In game.js file, we will start by adding some variables:

// Getting elements
var pad = document.getElementById("pad");
var ball = document.getElementById("ball");
var svg = document.getElementById("svgRoot");
var message = document.getElementById("message");

The ball will be defined by:

  • A position
  • A radius
  • A speed
  • A direction
  • Its previous position
// Ball
var ballRadius = ball.r.baseVal.value;
var ballX;
var ballY;
var previousBallPosition = { x: 0, y: 0 };
var ballDirectionX;
var ballDirectionY;
var ballSpeed = 10;

The pad will be defined by:

  • Width
  • Height
  • Position
  • Speed
  • Inertia value (just to make things smoother Sourire)
// Pad
var padWidth = pad.width.baseVal.value;
var padHeight = pad.height.baseVal.value;
var padX;
var padY;
var padSpeed = 0;
var inertia = 0.80;

Bricks will be saved in an array and will be defined by:

  • Width
  • Height
  • Margin between them
  • Lines count
  • Columns count

We also need an offset and a variable for counting destroyed bricks.

// Bricks
var bricks = [];
var destroyedBricksCount;
var brickWidth = 50;
var brickHeight = 20;
var bricksRows = 5;
var bricksCols = 20;
var bricksMargin = 15;
var bricksTop = 20;

And finally we also need the limits of the playground and a start date to compute session duration.

// Misc.
var minX = ballRadius;
var minY = ballRadius;
var maxX;
var maxY;
var startDate;

Handling a brick

To create a brick, we will need a function that will add a new element to the svg root. It will also configure each brick with required information:

var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
svg.appendChild(rect);
rect.setAttribute("width", brickWidth);
rect.setAttribute("height", brickHeight);
// Random green color 
var chars = "456789abcdef";
var color = "";
for (var i = 0; i < 2; i++) {
var rnd = Math.floor(chars.length * Math.random());
color += chars.charAt(rnd);
}
rect.setAttribute("fill", "#00" + color + "00");

The brick function will also provide a drawAndCollide function to display a brick and to check if there is a collision with the ball:

this.drawAndCollide = function () {
    if (isDead)
        return;
    // Drawing
    rect.setAttribute("x", position.x);
    rect.setAttribute("y", position.y);
 
    // Collision
    if (ballX + ballRadius < position.x || ballX - ballRadius > position.x + brickWidth)
        return;
 
    if (ballY + ballRadius < position.y || ballY - ballRadius > position.y + brickHeight)
        return;
 
    // Dead
    this.remove();
    isDead = true;
    destroyedBricksCount++;
 
    // Updating ball
    ballX = previousBallPosition.x;
    ballY = previousBallPosition.y;
 
    ballDirectionY *= -1.0;
};

Finally the full brick function will look like:

// Brick function
function Brick(x, y) {
    var isDead = false;
    var position = { x: x, y: y };
 
    var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    svg.appendChild(rect);
 
    rect.setAttribute("width", brickWidth);
    rect.setAttribute("height", brickHeight);
 
    // Random green color
    var chars = "456789abcdef";
    var color = "";
    for (var i = 0; i < 2; i++) {
        var rnd = Math.floor(chars.length * Math.random());
        color += chars.charAt(rnd);
    }
    rect.setAttribute("fill", "#00" + color + "00");
 
    this.drawAndCollide = function () {
        if (isDead)
            return;
        // Drawing
        rect.setAttribute("x", position.x);
        rect.setAttribute("y", position.y);
 
        // Collision
        if (ballX + ballRadius < position.x || ballX - ballRadius > position.x + brickWidth)
            return;
 
        if (ballY + ballRadius < position.y || ballY - ballRadius > position.y + brickHeight)
            return;
 
        // Dead
        this.remove();
        isDead = true;
        destroyedBricksCount++;
 
        // Updating ball
        ballX = previousBallPosition.x;
        ballY = previousBallPosition.y;
 
        ballDirectionY *= -1.0;
    };
 
    // Killing a brick
    this.remove = function () {
        if (isDead)
            return;
        svg.removeChild(rect);
    };
}

Collisions with the pad and the playground

The ball will also have collision functions that will handle collisions with the pad and the playground. These functions will have to update the ball direction when a collision will be detected.

// Collisions
function collideWithWindow() {
    if (ballX < minX) {
        ballX = minX;
        ballDirectionX *= -1.0;
    }
    else if (ballX > maxX) {
        ballX = maxX;
        ballDirectionX *= -1.0;
    }
 
    if (ballY < minY) {
        ballY = minY;
        ballDirectionY *= -1.0;
    }
    else if (ballY > maxY) {
        ballY = maxY;
        ballDirectionY *= -1.0;
        lost();
    }
}
 
function collideWithPad() {
    if (ballX + ballRadius < padX || ballX - ballRadius > padX + padWidth)
        return;
 
    if (ballY + ballRadius < padY)
        return;
 
    ballX = previousBallPosition.x;
    ballY = previousBallPosition.y;
    ballDirectionY *= -1.0;
 
    var dist = ballX - (padX + padWidth / 2);
 
    ballDirectionX = 2.0 * dist / padWidth;
 
    var square = Math.sqrt(ballDirectionX * ballDirectionX + ballDirectionY * ballDirectionY);
    ballDirectionX /= square;
    ballDirectionY /= square;
}

collideWithWindow checks the limits of the playground and collideWithPad checks the limits of the pad (We add a subtle change here: the horizontal speed of the ball will be computed using the distance with the center of the pad).

Moving the pad

You can control the pad with the mouse or with the left and right arrows. The movePad function is responsible for handling pad movement. It will also handle the inertia:

// Pad movement
function movePad() {
    padX += padSpeed;
 
    padSpeed *= inertia;
 
    if (padX < minX)
        padX = minX;
 
    if (padX + padWidth > maxX)
        padX = maxX - padWidth;
}

The code responsible for handling inputs is pretty simple:

registerMouseMove(document.getElementById("gameZone"), function (posx, posy, previousX, previousY) {
    padSpeed += (posx - previousX) * 0.2;
});
 
window.addEventListener('keydown', function (evt) {
    switch (evt.keyCode) {
        // Left arrow
        case 37:
            padSpeed -= 10;
            break;
        // Right arrow   
        case 39:
            padSpeed += 10;
            break;
    }
}, true);

Game loop

Before setting up the game loop we need a function to define the playground size. This function will be called when window is resized.

function checkWindow() {
maxX = window.innerWidth - minX;
maxY = window.innerHeight - 130 - 40 - minY;
padY = maxY - 30;
}

By the way, the game loop is the orchestrator here:

function gameLoop() {
    movePad();
 
    // Movements
    previousBallPosition.x = ballX;
    previousBallPosition.y = ballY;
    ballX += ballDirectionX * ballSpeed;
    ballY += ballDirectionY * ballSpeed;
 
    // Collisions
    collideWithWindow();
    collideWithPad();
 
    // Bricks
    for (var index = 0; index < bricks.length; index++) {
        bricks[index].drawAndCollide();
    }
 
    // Ball
    ball.setAttribute("cx", ballX);
    ball.setAttribute("cy", ballY);
 
    // Pad
    pad.setAttribute("x", padX);
    pad.setAttribute("y", padY);
    
    // Victory ?
    if (destroyedBricksCount == bricks.length) {
        win();
    }
}

Initialization and victory

The first step of initialization is creating bricks:

function generateBricks() {
    // Removing previous ones
    for (var index = 0; index < bricks.length; index++) {
        bricks[index].remove();
    }
 
    // Creating new ones
    var brickID = 0;
 
    var offset = (window.innerWidth - bricksCols * (brickWidth + bricksMargin)) / 2.0;
 
    for (var x = 0; x < bricksCols; x++) {
        for (var y = 0; y < bricksRows; y++) {
            bricks[brickID++] = new Brick(offset + x * (brickWidth + bricksMargin), y * (brickHeight + bricksMargin) + bricksTop);
        }
    }
}

The next step is about setting variables used by the game:

function initGame() {
    message.style.visibility = "hidden";
 
    checkWindow();
    
    padX = (window.innerWidth - padWidth) / 2.0;
 
    ballX = window.innerWidth / 2.0;
    ballY = maxY - 60;
 
    previousBallPosition.x = ballX;
    previousBallPosition.y = ballY;
    
    padSpeed = 0;
 
    ballDirectionX = Math.random();
    ballDirectionY = -1.0;
 
    generateBricks();
    gameLoop();
}

Every time the user will change the window size, we will have to reset the game:

window.onresize = initGame;

Then we have to attach an event handler to the new game button:

var gameIntervalID = -1;
function startGame() {
initGame();
destroyedBricksCount = 0;
if (gameIntervalID > -1)
clearInterval(gameIntervalID);
startDate = (new Date()).getTime(); ;
gameIntervalID = setInterval(gameLoop, 16);
}
document.getElementById("newGame").onclick = startGame;

Finally, we will add two functions for handling start and end of the game:

var gameIntervalID = -1;
function lost() {
    clearInterval(gameIntervalID);
    gameIntervalID = -1;
    
    message.innerHTML = "Game over !";
    message.style.visibility = "visible";
}
 
function win() {
    clearInterval(gameIntervalID);
    gameIntervalID = -1;
 
    var end = (new Date).getTime();
 
    message.innerHTML = "Victory ! (" + Math.round((end - startDate) / 1000) + "s)";
    message.style.visibility = "visible";
}

Conclusion

You are now a game developer! Using the power of accelerated graphics, we have developed a small game but with really interesting special effects!

Description: image

It's now up to you to update the game to make it the next blockbuster!

To go further

 

About the Author

David Catuhe is a developer evangelist for Microsoft France in charge of user experience development tools (from XAML to DirectX/XNA and HTML5). He defines himself as a geek and likes coding all that refer to graphics. Before working for Microsoft, he founded a company that developed a realtime 3D engine written with DirectX (www.vertice.fr).

 

Published at DZone with permission of David Catuhe, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Abdel Zoo replied on Sat, 2014/10/11 - 8:23am

thanks for your efforts العاب g9g 

 really I like it brother العاب صبايا  

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.