How to write a BrikBloc game with HTML5 SVG and Canvas
Join the DZone community and get the full member experience.
Join For Freethis 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
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
- internet explorer 9 /10 or other hardware-accelerated html5 modern browser
- visual studio 2010 sp1
-
web standards update :
http://visualstudiogallery.msdn.microsoft.com/a15c3ce9-f58f-42b7-8668-53f6cdc2cd83
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:
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.
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
)
// 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!
it's now up to you to update the game to make it the next blockbuster !
to go further
- learn about internet explorer 9/10 and why hardware acceleration matters
- my other html5 gaming blogs
- w3c html5
- w3c canvas
- w3c svg
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 ).
Opinions expressed by DZone contributors are their own.
Trending
-
Redefining DevOps: The Transformative Power of Containerization
-
Authorization: Get It Done Right, Get It Done Early
-
How to LINQ Between Java and SQL With JPAStreamer
-
Auto-Scaling Kinesis Data Streams Applications on Kubernetes
Comments