Care to make a cross-platform mobile game with HTML5? No need to dabble in Java or Objective-C? Bypass the app stores? Sounds like an instant win!

A handful of game developers are pushing the envelope of mobile HTML5 games at the moment. Check out the likes of Nutmeg1 and Lunch Bug2 for some shining examples. The great thing about these titles is that they work equally well on both mobile and desktop using the same code. Could HTML5 finally fulfill the holy grail of “write once, run anywhere”?

Getting Started

Before you start sketching the next Temple Run or Angry Birds, you should be aware of a few things that could dampen your excitement:

Performance
Mobile browsers are not traditionally known for their blazing JavaScript engines. With iOS 6 and Chrome beta for Android, though, things are improving fast.

Resolution
A veritable cornucopia of Android devices sport a wide range of resolutions. Not to mention the increased resolution and pixel density of the iPhone 4 and iPad 3.

Audio
Hope you enjoy the sound of silence. Audio support in mobile browsers is poor, to say the least. Lag is a major problem, as is the fact that most devices offer only a single channel. iOS won’t even load a sound until the user initiates the action. My advice is to hold tight and wait for browser vendors to sort this out.

Now, as a Web developer you’re used to dealing with the quirks of certain browsers and degrading gracefully and dealing with fragmented platforms. So, a few technical challenges won’t put you off, right? What’s more, all of these performance and audio problems are temporary. The mobile browser landscape is changing so quickly that these concerns will soon be a distant memory.

In this tutorial, we’ll make a relatively simple game that takes you through the basics and steers you away from pitfalls. The result will look like this:

It’s a fairly simple game, in which the user bursts floating bubbles before they reach the top of the screen. Imaginatively, I’ve titled our little endeavour Pop.

We’ll develop this in a number of distinct stages:

Cater to the multitude of viewports and optimize for mobile;

Look briefly at using the canvas API to draw to the screen;

Capture touch events;

Make a basic game loop;

Introduce sprites, or game “entities”;

Add collision detection and some simple maths to spice things up;

Add a bit of polish and some basic particle effects.

1. Setting The Stage

Enough of the background story. Fire up your favorite text editor, pour a strong brew of coffee, and let’s get our hands dirty.

As mentioned, there is a plethora of resolution sizes and pixel densities across devices. This means we’ll have to scale our canvas to fit the viewport. This could come at the price of a loss in quality, but one clever trick is to make the canvas small and then scale up, which provides a performance boost.

The meta viewport tag tells mobile browsers to disable user scaling and to render at full size rather than shrink the page down. The subsequent apple- prefixed meta tags allow the game to be bookmarked. On the iPhone, bookmarked apps do not display the toolbar at the bottom of the page, thus freeing up valuable real estate.

First, we create the POP namespace for our game. Being good developers, we don’t want to pollute the global namespace. In keeping good practice, we will declare all variables at the start of the program. Most of them are obvious: canvas refers to the canvas element in the HTML, and ctx enables us to access it via the JavaScript canvas API.

In POP.init, we grab a reference to our canvas element, get its context and adjust the canvas element’s dimensions to 480 × 320. The resize function, which is fired on resize and load events, adjusts the canvas’ style attribute for width and height accordingly while maintaining the ratio. Effectively, the canvas is still the same dimensions but has been scaled up using CSS. Try resizing your browser and you’ll see the canvas scale to fit.

If you tried that on your phone, you’ll notice that the address bar is still visible. Ugh! We can fix this by adding a few extra pixels to the document and then scrolling down to hide the address bar, like so:

Notice that we do this only for Android and iOS devices; otherwise, nasty scroll bars will appear. Also, we need to delay the firing of scrollTo to make sure it doesn’t get ignored on mobile Safari.

2. A Blank Canvas

Now that we’ve scaled our canvas snuggly to the viewport, let’s add the ability to draw some shapes.

Note: In this tutorial, we’re going to stick with basic geometric shapes. iOS 5 and Chrome beta for Android can handle a lot of image sprites at a high frame rate. Try that on Android 3.2 or lower and the frame rate will drop exponentially. Luckily, there is not much overhead when drawing circles, so we can have a lot of bubbles in our game without hampering performance on older devices.

Below, we’ve added a basic Draw object that allows us to clear the screen, draw a rectangle and circle, and add some text. Nothing mind-blowing yet. Mozilla Developers Network has excellent resources as always, replete with examples for drawing to the canvas6.

Our Draw object has methods for clearing the screen and drawing rectangles, circles and text. The benefit of abstracting these operations is that we don’t have to remember the exact canvas API calls, and we can now draw a circle with one line of code, rather than five.

Include the code above at the end of the POP.init function, and you should see a couple of shapes drawn to the canvas.

3. The Magic Touch

Just as we have the click event, mobile browsers provide methods for catching touch events.

The interesting parts of the code below are the touchstart, touchmove and touchend events. With the standard click event, we can get the coordinates from e.pageX and e.pageY. Touch events are slightly different. They contain a touches array, each element of which contains touch coordinates and other data. We only want the first touch, and we access it like so: e.touches[0].

Note: Android provides JavaScript access to multi-touch actions only since version 4.

We also call e.preventDefault(); when each event is fired to disable scrolling, zooming and any other action that would interrupt the flow of the game.

Now, try it out. Hmm, the circles are not appearing. A quick scratch of the head and a lightbulb moment! Because we’ve scaled the canvas, we need to account for this when mapping the touch to the screen’s position.

If your head is starting to hurt, a practical example should provide some relief. Imagine the player taps the 500 × 750 canvas above at 400,400. We need to translate that to 480 × 320 because, as far as the JavaScript is concerned, those are the dimensions of the canvas. So, the actual x coordinate is 400 divided by the scale; in this case, 400 ÷ 1.56 = 320.5.

Rather than calculating this on each touch event, we can calculate them after resizing. Add the following code to the start of the program, along with the other variable declarations:

// let's keep track of scale
// along with all initial declarations
// at the start of the program
scale: 1,
// the position of the canvas
// in relation to the screen
offset = {top: 0, left: 0},

In our resize function, after adjusting the canvas’ width and height, we make note of the current scale and offset:

4. In The Loop

A typical game loop goes something like this:

Poll user input,

Update characters and process collisions,

Render characters on the screen,

Repeat.

We could, of course, use setInterval, but there’s a shiny new toy in town named requestAnimationFrame. It promises smoother animation and is more battery-efficient. The bad news is that it’s not supported consistently across browsers. But Paul Irish has come to the rescue with a handy shim7.

Let’s go ahead and add the shim to the start of our current code base.

// Add this at the end of POP.init;
// it will then repeat continuously
POP.loop();
// Add the following functions after POP.init:
// this is where all entities will be moved
// and checked for collisions, etc.
update: function() {
},
// this is where we draw all the entities
render: function() {
POP.Draw.clear();
},
// the actual loop
// requests animation frame,
// then proceeds to update
// and render
loop: function() {
requestAnimFrame( POP.loop );
POP.update();
POP.render();
}

We call the loop at the end of POP.init. The POP.loop function in turn calls our POP.update and POP.render methods. requestAnimFrame ensures that the loop is called again, preferably at 60 frames per second. Note that we don’t have to worry about checking for input in our loop because we’re already listening for touch and click events, which is accessible through our POP.Input class.

The problem now is that our touches from the last step are immediately wiped off the screen. We need a better approach to remember what was drawn to the screen and where.

5. Spritely Will Do It

First, we add an entity array to keep track of all entities. This array will hold a reference to all touches, bubbles, particles and any other dynamic thing we want to add to the game.

// put this at start of program
entities: [],

Let’s create a Touch class that draws a circle at the point of contact, fades it out and then removes it.

The Touch class sets a number of properties when initiated. The x and y coordinates are passed as arguments, and we set the radius this.r to 5 pixels. We also set an initial opacity to 1 and the rate by which the touch fades to 0.05. There is also a remove flag that tells the main game loop whether to remove this from the entities array.

Crucially, the class has two main methods: update and render. We will call these from the corresponding part of our game loop.

We can then spawn a new instance of Touch in the game loop, and then move them via the update method:

// POP.update function
update: function() {
var i;
// spawn a new instance of Touch
// if the user has tapped the screen
if (POP.Input.tapped) {
POP.entities.push(new POP.Touch(POP.Input.x, POP.Input.y));
// set tapped back to false
// to avoid spawning a new touch
// in the next cycle
POP.Input.tapped = false;
}
// cycle through all entities and update as necessary
for (i = 0; i < POP.entities.length; i += 1) {
POP.entities[i].update();
// delete from array if remove property
// flag is set to true
if (POP.entities[i].remove) {
POP.entities.splice(i, 1);
}
}
},

Basically, if POP.Input.tapped is true, then we add a new instance of POP.Touch to our entities array. We then cycle through the entities array, calling the update method for each entity. Finally, if the entity is flagged for removal, we delete it from the array.

The POP.Bubble class is very similar to the Touch class, the main differences being that it doesn’t fade but moves upwards. The motion is achieved by updating the y position, this.y, in the update function. Here, we also check whether the bubble is off screen; if so, we flag it for removal.

Note: We could have created a base Entity class that both Touch and Bubble inherit from. But, I’d rather not open another can of worms about JavaScript prototypical inheritance versus classic at this point.

// Add at the start of the program
// the amount of game ticks until
// we spawn a bubble
nextBubble: 100,
// at the start of POP.update
// decrease our nextBubble counter
POP.nextBubble -= 1;
// if the counter is less than zero
if (POP.nextBubble < 0) {
// put a new instance of bubble into our entities array
POP.entities.push(new POP.Bubble());
// reset the counter with a random value
POP.nextBubble = ( Math.random() * 100 ) + 100;
}

Above, we have added a random timer to our game loop that will spawn an instance of Bubble at a random position. At the start of the game, we set nextBubble with a value of 100. This is subtracted on each game tick and, when it reaches 0, we spawn a bubble and reset the nextBubble counter.

6. Putting It Together

First of all, there is not yet any notion of collision detection. We can add that with a simple function. The math behind this is basic geometry, which you can brush up on at Wolfram MathWorld8.

And let’s make them oscillate from side to side, so that they are harder to hit:

// the amount by which the bubble
// will move from side to side
this.waveSize = 5 + this.r;
// we need to remember the original
// x position for our sine wave calculation
this.xConstant = this.x;
this.remove = false;
this.update = function() {
// a sine wave is commonly a function of time
var time = new Date().getTime() * 0.002;
this.y -= this.speed;
// the x coordinate to follow a sine wave
this.x = this.waveSize * Math.sin(time) + this.xConstant;
// the rest of the class is unchanged

Accuracy is obtained by dividing the number of hits by the number of taps, multiplied by 100, which gives us a nice percentage. Note that ~~(POP.score.accuracy) is a quick way (i.e. a hack) to round floats down to integers.

It’s fairly obvious what is going on here. Using some basic acceleration so that the particles speed up as the reach the surface is a nice touch. Again, this math and physics are beyond the scope of this article, but for those interested, Skookum Digital Works explains it in depth10.

To create the particle effect, we push several particles into our entities array whenever a bubble is hit:

Here, we’ve reused our sine wave solution for the bubbles to make the waves move gently to and fro. Feeling seasick yet?

Final Thoughts

Phew! That was fun. Hope you enjoyed this short forage into tricks and techniques for making an HTML5 game. We’ve managed to create a very simple game that works on most smartphones as well as modern browsers. Here are some things you could consider doing:

Store high scores using local storage.

Add a splash screen and a “Game over” screen.

Enable power-ups.

Add audio. Contrary to what I said at the beginning of this article, this isn’t impossible, just a bit of a headache. One technique is to use audio sprites (kind of like CSS image sprites); Remy Sharp breaks it down11.

Let your imagination run wild!

If you are interested in further exploring the possibilities of mobile HTML5 games, I recommend test-driving a couple of frameworks to see what works for you. Juho Vepsäläinen offers a useful summary of most game engines12. If you’re willing to invest a little cash, then Impact13 is a great starting point, with thorough documentation and lively helpful forums. And the impressive X-Type14 demonstrates what is possible. Not bad, eh?

Brad

You should pick one up on cl/ebay. But it has nothing to do with touch events. The escaped just counts up every second or two and there is nothing on the screen. And touch events regiester as click events on the desktop so minus any errors I would think it should work.

When I touch on my WP7 i can see the event register fine. We just need something to shoot at.

Eoin McGrath

~ is the bitwise operator for binary NOT. Applying it once swaps every bit that was 1 to 0 and 0 to 1. Doing so again and it switches the number back to what it was before, except that it drops anything after the decimal point. Effectively, it rounds a number down, to the nearest whole number.

Bertrand

Interesting, thanks!
I know nothing in js, but I wonder if there is not a small bug in update function: after removing an element i, the next one will not be updated. Variable i should not be incremented when using splice().

Matt Stone

Lexi

Thanks for the simplified tutorial. I’m actually thinking of designing my ow mobile game as well and this really helps :) It’s a good thing web dev and mobile game development are similar in a lot of ways :)
eacsoft.com/

Jason

Carl

Is it possible to make this game to an android app? Now you only can run it from a browser, right?
It would have been awesome with a tutorial on how to do that! For an example how to make the game to an android app using WebView or something.

Thanga Durai

Alejo

Loved the performance and the way it works on mobile. Fully tested and happy. Definitely is a must to read. Already building my first game based on this tutorial and works great. Guess all my games are to be based at the end on this. Nothing else to say. Thanks a Lot Eoin.

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

Subscribe to our email newsletter for useful tips and valuable resources, sent out every second Tuesday.

Meet Smashing Book #5, our new book on real-life responsive design. With front-end techniques and patterns from actual projects, it's a playbook to master all the tricky facets and hurdles of responsive design. Save 25% today.

Fixing RWD issues can be quite easy — once you understand exactly why they come up. The Mobile Web Handbook will help you understand technical issues on mobile and how to deal with them effectively.

Hungry for more content? Over 60 eBooks are waiting to be discovered in our lovely Smashing Library. And guess what? You can watch Smashing Conference talks there, too.

SmashingConf isn't the eighth wonder of the world, but we are pretty close. Join us at at the shores of Santa Monica for SmashingConf LA on April 27–30 or at SmashingConf NYC on June 15–18. You won't be disappointed.