# Build Your First Game With HTML5

HTML5 is growing up faster than anyone could have imagined. Powerful and professional solutions are already being developed...even in the gaming world! Check out the hundreds of HTML5 games on Envato Market.

Today, you'll make your first game using Box2D and HTML5's canvas tag.

### What is Box2D?

Box2D is an open source and popular engine that simulates 2D physics for making games and applications. Primarily written in C++, it has been converted to numerous languages by community contributors.

With the same methods and objects, you have the ability to make your games' physics in many languages, such as Objective C (iPhone/iPad), Actionscript 3.0 (Web), HTML 5 (Web), etc.

## Step 1 - Setting up your Project

To begin developing your demo, download the Box2D engine for HTML5 here. Next, create a new HTML file with the following structure (copy js and lib directories from box2d-js project to your game folder).

Now, you must insert the necessary files to run box2D into your HTML file:

 1   2   3   4   5   6   7   8   9   10   11   12   13   14   15   16   17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32   33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48   49   50   51   52   53   54   55   56   57   58   59   60   61   62   63   64   65   66   67  

Yep, that's a huge number of HTTP requests!

Please note that, for deployment, it's highly recommended that you concatenate all of these resources into one script file.

Next, create two more scripts inside the /js/ folder, called "box2dutils.js" and "game.js".

• box2dutils.js - it's a copy and paste from some demos that come with box2dlib, and is important for drawing functions (I will also explain some important parts here).
• game.js - the game, itself; this is where we create the platforms, the player, apply the keyboard interactions, etc.

Copy and paste the following code into box2dutils.js. Don't worry! I'll explain it bit by bit!

 1 function drawWorld(world, context) {  2  for (var j = world.m_jointList; j; j = j.m_next) {  3  drawJoint(j, context);  4  }  5  for (var b = world.m_bodyList; b; b = b.m_next) {  6  for (var s = b.GetShapeList(); s != null; s = s.GetNext()) {  7  drawShape(s, context);  8  }  9  }  10 }  11 function drawJoint(joint, context) {  12  var b1 = joint.m_body1;  13  var b2 = joint.m_body2;  14  var x1 = b1.m_position;  15  var x2 = b2.m_position;  16  var p1 = joint.GetAnchor1();  17  var p2 = joint.GetAnchor2();  18  context.strokeStyle = '#00eeee';  19  context.beginPath();  20  switch (joint.m_type) {  21  case b2Joint.e_distanceJoint:  22  context.moveTo(p1.x, p1.y);  23  context.lineTo(p2.x, p2.y);  24  break;  25 26  case b2Joint.e_pulleyJoint:  27  // TODO  28  break;  29 30  default:  31  if (b1 == world.m_groundBody) {  32  context.moveTo(p1.x, p1.y);  33  context.lineTo(x2.x, x2.y);  34  }  35  else if (b2 == world.m_groundBody) {  36  context.moveTo(p1.x, p1.y);  37  context.lineTo(x1.x, x1.y);  38  }  39  else {  40  context.moveTo(x1.x, x1.y);  41  context.lineTo(p1.x, p1.y);  42  context.lineTo(x2.x, x2.y);  43  context.lineTo(p2.x, p2.y);  44  }  45  break;  46  }  47  context.stroke();  48 }  49 function drawShape(shape, context) {  50  context.strokeStyle = '#000000';  51  context.beginPath();  52  switch (shape.m_type) {  53  case b2Shape.e_circleShape:  54  {  55  var circle = shape;  56  var pos = circle.m_position;  57  var r = circle.m_radius;  58  var segments = 16.0;  59  var theta = 0.0;  60  var dtheta = 2.0 * Math.PI / segments;  61  // draw circle  62  context.moveTo(pos.x + r, pos.y);  63  for (var i = 0; i < segments; i++) {  64  var d = new b2Vec2(r * Math.cos(theta), r * Math.sin(theta));  65  var v = b2Math.AddVV(pos, d);  66  context.lineTo(v.x, v.y);  67  theta += dtheta;  68  }  69  context.lineTo(pos.x + r, pos.y);  70   71  // draw radius  72  context.moveTo(pos.x, pos.y);  73  var ax = circle.m_R.col1;  74  var pos2 = new b2Vec2(pos.x + r * ax.x, pos.y + r * ax.y);  75  context.lineTo(pos2.x, pos2.y);  76  }  77  break;  78  case b2Shape.e_polyShape:  79  {  80  var poly = shape;  81  var tV = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[0]));  82  context.moveTo(tV.x, tV.y);  83  for (var i = 0; i < poly.m_vertexCount; i++) {  84  var v = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[i]));  85  context.lineTo(v.x, v.y);  86  }  87  context.lineTo(tV.x, tV.y);  88  }  89  break;  90  }  91  context.stroke();  92 }  93 94 95 function createWorld() {  96  var worldAABB = new b2AABB();  97  worldAABB.minVertex.Set(-1000, -1000);  98  worldAABB.maxVertex.Set(1000, 1000);  99  var gravity = new b2Vec2(0, 300);  100  var doSleep = true;  101  var world = new b2World(worldAABB, gravity, doSleep);  102  return world;  103 }  104 105 function createGround(world) {  106  var groundSd = new b2BoxDef();  107  groundSd.extents.Set(1000, 50);  108  groundSd.restitution = 0.2;  109  var groundBd = new b2BodyDef();  110  groundBd.AddShape(groundSd);  111  groundBd.position.Set(-500, 340);  112  return world.CreateBody(groundBd)  113 }  114 115 function createBall(world, x, y) {  116  var ballSd = new b2CircleDef();  117  ballSd.density = 1.0;  118  ballSd.radius = 20;  119  ballSd.restitution = 1.0;  120  ballSd.friction = 0;  121  var ballBd = new b2BodyDef();  122  ballBd.AddShape(ballSd);  123  ballBd.position.Set(x,y);  124  return world.CreateBody(ballBd);  125 }  126 127 function createBox(world, x, y, width, height, fixed, userData) {  128  if (typeof(fixed) == 'undefined') fixed = true;  129  var boxSd = new b2BoxDef();  130  if (!fixed) boxSd.density = 1.0;  131   132  boxSd.userData = userData;  133   134  boxSd.extents.Set(width, height);  135  var boxBd = new b2BodyDef();  136  boxBd.AddShape(boxSd);  137  boxBd.position.Set(x,y);  138  return world.CreateBody(boxBd)  139 } 

## Step 2 - Developing the Game

Open the index.html file that you previously created, and add a canvas element (600x400) within the body element. This is where we'll work with the HTML5 drawing API:

 1  

Also, while you're here, reference game.js and box2dutils.js.

 1   2  

That'll do it for the HTML! Let's work on the fun JavaScript now!

Open game.js, and insert the code below:

 1 // some variables that we gonna use in this demo  2 var initId = 0;  3 var player = function(){  4  this.object = null;  5  this.canJump = false;  6 };  7 var world;  8 var ctx;  9 var canvasWidth;  10 var canvasHeight;  11 var keys = [];  12 13 // HTML5 onLoad event  14 Event.observe(window, 'load', function() {  15  world = createWorld(); // box2DWorld  16  ctx = $('game').getContext('2d'); // 2  17  var canvasElm =$('game');  18  canvasWidth = parseInt(canvasElm.width);  19  canvasHeight = parseInt(canvasElm.height);  20  initGame(); // 3  21  step(); // 4  22   23 // 5  24  window.addEventListener('keydown',handleKeyDown,true);  25  window.addEventListener('keyup',handleKeyUp,true);  26 }); 

### Box2DWorld - that's why we're here

Okay, let's figure out what this chunk of code does!

Box2DWorld is one of the classes that is made available, via the core of box2d. Its function is simple: combine everything into one class. In box2DWorld, you have the bodies definition and collisions manager of your game or application.

Keep the game.js and box2dutils.js files open, and search for the createWorld() function within box2dutils.js.

 1 function createWorld() {  2  // here we create our world settings for collisions  3  var worldAABB = new b2AABB();  4  worldAABB.minVertex.Set(-1000, -1000);  5  worldAABB.maxVertex.Set(1000, 1000);  6  // set gravity vector  7  var gravity = new b2Vec2(0, 300);  8  var doSleep = true;  9  // init our world and return its value  10  var world = new b2World(worldAABB, gravity, doSleep);  11  return world;  12 } 

It's quite simple to create the box2DWorld.

### Back to game.js

Refer to the commented numbers in the two blocks of code above. On number two, we retrieve the canvas element's context by using the selector API (looks like jQuery or MooTools selectors, don't they?). On number three, we have a new interesting function: initGame(). This is where we create the scenery.

Copy and paste the code below into game.js, and then we'll review it together.

 1 function initGame(){  2  // create 2 big platforms  3  createBox(world, 3, 230, 60, 180, true, 'ground');  4  createBox(world, 560, 360, 50, 50, true, 'ground');  5   6  // create small platforms  7  for (var i = 0; i < 5; i++){  8  createBox(world, 150+(80*i), 360, 5, 40+(i*15), true, 'ground');  9  }  10   11  // create player ball  12  var ballSd = new b2CircleDef();  13  ballSd.density = 0.1;  14  ballSd.radius = 12;  15  ballSd.restitution = 0.5;  16  ballSd.friction = 1;  17  ballSd.userData = 'player';  18  var ballBd = new b2BodyDef();  19  ballBd.linearDamping = .03;  20  ballBd.allowSleep = false;  21  ballBd.AddShape(ballSd);  22  ballBd.position.Set(20,0);  23  player.object = world.CreateBody(ballBd);  24   25 }  26 27 

Inside box2dutils.js, we've created a function, called createBox. This creates a static rectangle body.

 28 29 function createBox(world, x, y, width, height, fixed, userData) {  30  if (typeof(fixed) == 'undefined') fixed = true;  31  //1  32 var boxSd = new b2BoxDef();  33  if (!fixed) boxSd.density = 1.0;  34  //2  35  boxSd.userData = userData;  36  //3  37  boxSd.extents.Set(width, height);  38 39  //4  40  var boxBd = new b2BodyDef();  41  boxBd.AddShape(boxSd);  42  //5  43  boxBd.position.Set(x,y);  44  //6  45  return world.CreateBody(boxBd)  46 } 

### Box2DBody

A Box2DBody has some unique characteristics:

• It can be static (not affected by collisions impacts), kinematic (it isn't affected by collisions, but it can be moved by your mouse, for example), or dynamic (interacts with everything)
• Must have a shape definition, and should indicate how the object appears
• May have more than one fixture, which indicates how the object will interact with collisions
• Its position is set by the center of your object, not the left top edge as many other engines do.

#### Reviewing the code:

1. Here, we create one shape definition that will be a square or rectangle, and setup its density (how often it gonna be moved, or rotate by forces).
2. We setup the userData, usually you setup graphics objects here, but in this example, I just setup strings that will be the identifier of the type of the object for collisions. This parameter doesn't affect physics algorithms.
3. Setup half of the size of my box (it's a line from the position point, or the center point of the object to a corner)
4. We create the body definition, and add to it the box shape definition.
5. Setup the position.
6. Create the body in the world and return its value.

### Creating the Player Ball Body

I've coded the player (ball) directly in the game.js file. It follows the same sequence of creating boxes, but, this time, it's a ball.

 1 var ballSd = new b2CircleDef();  2  ballSd.density = 0.1;  3  ballSd.radius = 12;  4  ballSd.restitution = 0.5;  5  ballSd.friction = 1;  6  ballSd.userData = 'player';  7  var ballBd = new b2BodyDef();  8  ballBd.linearDamping = .03;  9  ballBd.allowSleep = false;  10  ballBd.AddShape(ballSd);  11  ballBd.position.Set(20,0);  12  player.object = world.CreateBody(ballBd); 

So how do we create a body, step by step?

1. Create the shape, fixture and sensor definition
2. Create the body definition
4. Create the body in the world

### Box2DCircle

As I noted earlier, this follows the same creation process of a box, but now you must set some new parameters.

• radius - This is the length of a line from the center of the circle to any point on its edge.
• restitution - How the ball will lose, or gain force when collides with other body.
• friction - How the ball will roll.

### Box2DBody - More Properties

• damping is used to reduce the velocity of the body - there's angular damping and linear damping.
• sleep in box2D, bodies can sleep to solve performance issues. For example, let's suppose you are developing a platform game, and the level is defined by a 6000x400 screen. Why do you need to perform physics for objects that are off screen? You don't; that's the point! So the correct choice is to put them to sleep, and improve your game's performance.

We've already created our world; you can test the code that you have so far. You'll see the player falling above the west platform.

Now, if you tried to run the demo, you should be wondering, why is the page as barren as white paper?

Always remember: Box2D doesn't render; it only calculates physics.

## Step 3 - Rendering Time

Next, let's render the box2DWorld.

Open your game.js script, and add the following code:

 1 function step() {  2   3  var stepping = false;  4  var timeStep = 1.0/60;  5  var iteration = 1;  6  // 1  7  world.Step(timeStep, iteration);  8  // 2  9  ctx.clearRect(0, 0, canvasWidth, canvasHeight);  10  drawWorld(world, ctx);  11  // 3  12  setTimeout('step()', 10);  13 } 

#### What we accomplish here:

1. Instructed box2dWorld to perform physics simulations
2. Cleared canvas screen and draw again
3. Execute the step() function again in ten milliseconds

With this bit of code, we are now working with physics and drawing. You can test yourself, and watch for a falling ball, as demonstrated below:

### drawWorld in box2dutils.js

 1 function drawWorld(world, context) {  2  for (var j = world.m_jointList; j; j = j.m_next) {  3  drawJoint(j, context);  4  }  5  for (var b = world.m_bodyList; b; b = b.m_next) {  6  for (var s = b.GetShapeList(); s != null; s = s.GetNext()) {  7  drawShape(s, context);  8  }  9  }  10 } 

What we've written above is a debug function that draws our world into the canvas, using the graphics API provided by HTML5's Canvas API.

The first loop draws all joints. We didn't use joints in this article. They are a bit complex for a first demo, but, nonetheless, they're essential for your games. They allow you to create very interesting bodies.

The second loop draws all bodies, which is why we're here!

 1 function drawShape(shape, context) {  2  context.strokeStyle = '#000000';  3  context.beginPath();  4  switch (shape.m_type) {  5  case b2Shape.e_circleShape:  6  {  7  var circle = shape;  8  var pos = circle.m_position;  9  var r = circle.m_radius;  10  var segments = 16.0;  11  var theta = 0.0;  12  var dtheta = 2.0 * Math.PI / segments;  13  // draw circle  14  context.moveTo(pos.x + r, pos.y);  15  for (var i = 0; i < segments; i++) {  16  var d = new b2Vec2(r * Math.cos(theta), r * Math.sin(theta));  17  var v = b2Math.AddVV(pos, d);  18  context.lineTo(v.x, v.y);  19  theta += dtheta;  20  }  21  context.lineTo(pos.x + r, pos.y);  22   23  // draw radius  24  context.moveTo(pos.x, pos.y);  25  var ax = circle.m_R.col1;  26  var pos2 = new b2Vec2(pos.x + r * ax.x, pos.y + r * ax.y);  27  context.lineTo(pos2.x, pos2.y);  28  }  29  break;  30  case b2Shape.e_polyShape:  31  {  32  var poly = shape;  33  var tV = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[0]));  34  context.moveTo(tV.x, tV.y);  35  for (var i = 0; i < poly.m_vertexCount; i++) {  36  var v = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[i]));  37  context.lineTo(v.x, v.y);  38  }  39  context.lineTo(tV.x, tV.y);  40  }  41  break;  42  }  43  context.stroke();  44 } 

We're looping through every vertices of the object and drawing it with lines (context.moveTo and context.lineTo). Now, it's useful to have an example... but not so useful in practice. When you use graphics, you only need to pay attention to the bodies' positioning. You don't need to loop vertices, as this demo does.

## Step 4 - Interactivity

A game without interactivity is a movie, and a movie with interactivity is a game.

Let's develop the keyboard arrow functionality to jump and move the ball.

Add the following code to your game.js file:

 1 function handleKeyDown(evt){  2  keys[evt.keyCode] = true;  3 }  4 5 6 function handleKeyUp(evt){  7  keys[evt.keyCode] = false;  8 }  9 10 // disable vertical scrolling from arrows :)  11 document.onkeydown=function(){return event.keyCode!=38 && event.keyCode!=40} 

With handleKeyDown and handleKeyUp, we setup an array which tracks every key the user types. With document.onkeydown, we disable the browser's native vertical scrolling function for up and down arrows. Have you ever played an HTML5 game, and when you jump, the player, enemies and objects go off screen? That won't be an issue now.

Add this next bit of code to the beginning of your step() function:

 1 handleInteractions(); 

And outside, declare the function:

 1 function handleInteractions(){  2  // up arrow  3  // 1  4  var collision = world.m_contactList;  5  player.canJump = false;  6  if (collision != null){  7  if (collision.GetShape1().GetUserData() == 'player' || collision.GetShape2().GetUserData() == 'player'){  8  if ((collision.GetShape1().GetUserData() == 'ground' || collision.GetShape2().GetUserData() == 'ground')){  9  var playerObj = (collision.GetShape1().GetUserData() == 'player' ? collision.GetShape1().GetPosition() : collision.GetShape2().GetPosition());  10  var groundObj = (collision.GetShape1().GetUserData() == 'ground' ? collision.GetShape1().GetPosition() : collision.GetShape2().GetPosition());  11  if (playerObj.y < groundObj.y){  12  player.canJump = true;  13  }  14  }  15  }  16  }  17  // 2  18  var vel = player.object.GetLinearVelocity();  19  // 3  20  if (keys[38] && player.canJump){  21  vel.y = -150;  22  }  23   24  // 4  25  // left/right arrows  26  if (keys[37]){  27  vel.x = -60;  28  }  29  else if (keys[39]){  30  vel.x = 60;  31  }  32   33  // 5  34  player.object.SetLinearVelocity(vel);  35 } 

The most complicated piece of the code above is the first one, where we check for a collision, and write some conditions to determine if the shape1 or the shape2 is the player. If it is, we verify if shape1 or shape2 is a ground object. Again, if so, the player is colliding with the ground. Next, we check if the player is above the ground. If that's the case, then the player can jump.

On the second commented line (2), we retrieve the LinearVelocity of the player.

The third and forth commented regions verify if arrows are being pressed, and adjust the velocity vector, accordingly.

In the fifth region, we setup the player with the new velocity vector.

The interactions are now done! But there's no objective, We just jump, jump, jump… and jump!

## Step 5 - "You Win" Message

Add the code below to the beginning of your LinearVelocity function:

 1  if (player.object.GetCenterPosition().y > canvasHeight){  2  player.object.SetCenterPosition(new b2Vec2(20,0),0)  3  }  4  else if (player.object.GetCenterPosition().x > canvasWidth-50){  5  showWin();  6  return;  7  } 
• The first condition determines if the player falls, and should be transported back to the start point (above the west platform).
• The second condition checks if the player is above the second platform, and won the game. Here's the showWin() function.
 1 function showWin(){  2  ctx.fillStyle = '#000';  3  ctx.font = '30px verdana';  4  ctx.textBaseline = 'top';  5  ctx.fillText('Ye! you made it!', 30, 0);  6  ctx.fillText('thank you, andersonferminiano.com', 30, 30);  7  ctx.fillText('@andferminiano', 30, 60);  8 } 

And that's it! You've just completed your first simple game with HTML5 and Box2D. Congratulations!

If you need a simpler solution, you could check out the selection of HTML5 games on Envato Market, many of which come with source code for you to investigate and customize to fit your own needs.