Performance of browser-based games

Until recently, performance of browser-based games for mobile devices has lagged significantly behind desktop performance. If you wanted to create a Canvas-based mobile game, performance was terrible and you needed to build your game around the limitations of the platform. Developing a usable game meant using tricks like scaling up from very low resolutions or doing partial screen updates instead of full refreshes, meaning your game design was limited by the platform’s weaknesses rather than your creativity.

Luckily, this has changed. Browser vendors are rapidly improving their mobile performance:

  • iOS5 now ships with Nitro Javascript
  • Chrome for Android browser is now available on Android 4 (Ice Cream Sandwich)
  • Windows Phone 7 Mango launched IE9 mobile with hardware acceleration

All feature a GPU hardware-accelerated HTML5 Canvas element and both feature multi-touch support inside of the browser, a must for any but the simplest games. While Chrome for Android still have some significant work to do on Canvas performance, this now seems like an inevitability rather than a hopeful prayer.

Developing HTML5 games that work in the mobile browser comes with its own special set of requirements. You’ll first need to have an idea of the number of sprites you can push on the screen at once. Next you’ll want to maximize your game to the size of screen so that users don’t have to squint to play your game. Next you’ll need to add touch controls so the game will be playable without a keyboard. Finally you’ll want to consider adding a number of pieces of meta-data to allow your page to be used a home-screen application and have it show up with the right icon.

Performance Considerations

While mobile HTML5 game performance has increased significantly, you do still need to be aware of the limitations of the two dominant platforms: iOS and Android.

You have two primary options when building an HTML5 game: either build it with Canvas or use CSS sprites. For example, before iOS 5, you’d achieve much better performance in general using CSS sprites, provided you weren’t moving too many of them each frame. This was (and generally still is) the case with Android. Browsers have been optimizing the rendering of HTML elements for a long, so unless you are moving a full page’s worth of tiles and sprites, CSS sprites are still something to consider.

Now with hardware acceleration, Canvas performance has reached a level where where full screen action games at CSS pixel resolution are possible.

The rub is that most of these devices have resolutions that far exceed CSS pixel resolution. In iPhone 4, the resolution of the retina display exposed to web developers was unchanged at 320×480, while the actual screen resolution is 640×960. Since the resolution of the canvas tag is independent from how it’s rendered on the screen, you can create a full resolution canvas, set it to 320×480 CSS pixel dimensions and be pushing 4 times as many pixels through to the display. This will look crisp and nice, but you unless you are doing partial screen refreshes, pumping that many pixels through the Canvas tag is currently out of the reach of HTML5 mobile games.

These limitations means that as of the current generation of devices, you should be targeting a CSS pixel resolution in your game (many native apps still don’t necessarily all have Retina-display scaled assets, so this shouldn’t be viewed as a huge failing).

The good news is that at this resolution you have a little bit of breathing room with how much you render on the screen. I’ve written a simple test script (runnable at that renders a number of moving 30×31 pixels sprites onto an area 320×320 pixels in size using a number of different methods (including CSS sprites and plain Canvas). Running this test script on a iPhone 4, an iPad 2 and a Galaxy Nexus in Chrome for Android results in the following performance for CSS sprites (background images) and Canvas sprites:

All three devices are able to draw over 100 sprites per frame (with a full canvas clear) and render at least 30 fps. While 100 sprites is not a limitless number of sprites, it’s enough for many uses cases. For games with tiled backgrounds, you’ll still want to prerender to offscreen canvas buffers instead of redrawing every tile each frame, but a fullscreen animated game is certainly doable.

Given that every platform can still render double digit frames per second at 1000 sprites per frame, you have some extra leeway to do some significant pre-rendering and offscreen rendering every few frames without grinding your game to a halt. The rest of this article will assume you’re working on a Canvas based game as that’s where the performance boosts are going to be. If you’re working on a CSS sprite-based game, some of the pieces (such as canvas resizing) won’t apply, but much will still be applicable.

Viewport Considerations

Once you’ve got an HTML5 game spec’d out within the performance capabilities of the platform (or are converting an existing game for mobile play) you’ll need to consider how that game will actually look and play on mobile. Many web games on the desktop are generally confined to a play area of a specific size with additional stuff (ads!) wrapping around the play area.

On mobile, this won’t fly. Mobile devices have such limited screen real estate as it is that when a player is playing your game, it behooves you to maximize the play area to the extent that you can. This might seem easy in principle, but since different devices have different resolutions and aspect ratios there’s often only so much you can do.

Your main options are either:

  1. Resize the canvas to fill the entire screen.
  2. Resize the canvas to fill majority of the screen, keeping the existing aspect ratio.

Option 2 will give you infinitely less trouble than option 1, as it means your game code doesn’t need to worry about having a different sized playing area depending on the device. On the flip side, it also means you’ll be constraining the viewport of your game smaller than the full size of the device. For some games you’ll want the size and aspect ratio of the game to stay consistent so that enemies appear and disappear in consistent ways. For a 2d platformer, you might consider going with option 1 as adjusting slightly the amount of the level that the player sees while playing isn’t going to dramatically affect gameplay but will make the game look (and play) more like a native game.

Game Code Organization

At Bocoup, my colleagues and I often laze about in antique leather armchairs, sipping Mai Tais, waxing rhetoric about important issues-of-the-day including international politics and automatic semicolon insertion. One thing I find fascinating is how people working on different types of projects have different wisdom to share: best practices for jQuery plugins are different than those for Facebook apps, and tips for Backbone.js ecommerce sites may not be useful when developing real-time strategy games.

What I’d like to share in this article is some code organization tips and tricks I’ve learned while making HTML5 games. I’ve tried to keep them as generally useful as possible, but you’ll definitely get the most out of this if you make games like I do.

First I’ll discuss organizing JavaScript code into files and modules. Then I’ll talk about code sharing approaches such as component systems. Lastly I’ll share some ideas for writing data-driven code in games.

Files and Modules

It should go without saying that a large application all stuffed into one file is a maintenance nightmare. Still, even now, the logistics of organizing JavaScript in separate files are being ironed out. First let’s look at the file issue itself, then the more complex issue of what sorts of modules those files contain.

Many Files in Development, Concat in Production

When setting up a new JavaScript project, I recommend using grunt, a build tool that has built-in tasks for concatenating all your files into one, then minifying the result. You want users to end up downloading just one minified JavaScript file. This is great in production, since it reduces HTTP requests and download sizes. In development, it’s not so good: having readable code in separate files is necessary for efficient debugging.

I recommend having something like this in your index.html:

This way you can comment out app.js and uncomment the source files for easy development.

However, this isn’t ideal. One thing you might do is modify your build process to have options to build for development or for production, saving you the effort of manually commenting / uncommenting lines. No build tools do this out of the box as far as I know, but for some projects this extra effort of customizing your build process may be worthwhile.

Source Maps

Google Chrome has a cool new feature called Source Maps that solves this problem. When you use a JavaScript concatenator/minifier that supports Source Maps, the compiler will add a comment to the code that refers to the source map (a header can also be used). The source map contains all the necessary information for linking from the compiled code to the source file. As a result, development tools that support Source Maps will understand what file some given code originally came from. There is no longer any issue debugging / developing with minified code.

Right now the Closure compiler and Google Chrome are the only compiler and browser that support Source Maps, so it can only be used on certain projects. Still, if more tools start to support it, this may be the future of debugging JavaScript.

IIFEs and Namespaces

Now that you have a build process that intelligently handles multiple files, what actually goes in those files?

A Console Experience on the Web

Every new generation of consoles has brought with it services such as marketplaces, achievements and gamer profiles, which have made it easier for players to instantly connect with friends, as well as being able to discover, purchase and find new ways to enjoy games.

In this article I will be discussing 3 main features of traditional gaming systems, and compare them with the offerings of the open web, and discussing how you can leverage these offerings to bring in new audiences for your games.


What kind of console game doesn’t support controllers? Analog input can make most games, from platformers to racers, easier and undoubtedly more fun to play. Games like Super Meat Boy or FIFA, while supporting keyboards, are designed to be played with controllers. The social, couch-based gaming of traditional consoles required a method of input that was simple, unobtrusive and ergonomic.

What does the open web need?

An interface that allows players (and their friends) to simply plug in any existing controller and be able to start a game without downloading any special drivers, browsers, or plugins. Unfortunately, there are a few problems with that ideal situation:

  • Most controllers require driver installations on almost every platform out there (The exception is XBOX Controller for Windows)
  • Some controllers flat-out refuse to work on certain platforms
  • Input values vary by controller
  • Not all browsers support/are working on Game Controller APIs

What’s currently available?

Clearly the folks at Mozilla and Google see the need for HTML5 to catch up to consoles, as their rapid work on Gamepad-specific APIs shows. Mozilla Firefox has a special Gamepad build. All Chrome builds require a change in chrome://flags before you can read controller input.

In terms of controller support, here’s what you can use:

  • Windows
    • XBOX360 Controller for Windows (works best)
    • PLAYSTATION DualShock3 controller – can trick Windows into reading it as XBOX360 controller using MotionInJoy
    • Logitech Gamepads such as the F310, F510 and F710
    • As a rule of thumb: any controller which emulates the XBOX360 controller should work.
  • Linux
    • Controllers in the Windows list above should all work.
    • Due to the variety of distributions and kernel versions out there, it’s hard to provide a concrete list of supported controllers, but anything using the USB HID interface should work.
  • Mac
    • PLAYSTATION DualShock3 controller is supported out-of-the-box
    • XBOX360 Controller for Windows, using special software from Colin Munro

What tools do I use?

There are a few libraries out there that ease the pain of having to customize button assignments and API calls across Firefox and Chrome.

  • Gamepad.js is clean, works well, and is super simple to work with
  • Input.js is another one that tries to abstract away the Gamepad API. It’s built by a Mozilla Engineer and is being developed as part of their Paladin gaming initiative.
  • Raw API calls. It isn’t too hard, but you’ll have to worry about button mapping across a variety of controllers.

Canvas Utility Belt

The past year has seen wonderful growth in the popularity of 2D Canvas; it’s been great to see so many people getting comfortable with the 2D context. Canvas is almost synonomous with HTML5 gaming and supported in all modern browsers including Chrome, Firefox, and Internet Explorer 10 and 9.

One thing that many people take for granted is the “bottom to top” canvas drawing order; putting down the background first, then objects in the middle of the scene, and finally drawing the foreground.

It’s true that this is how canvas works by default, and there’s a specific name for it; it’s called the source-over global composite operation (GCO).

What many people don’t know is that you can reverse this order – by setting ctx.globalCompositeOperation = destination-over, you can actually draw the background last, and it will go under what’s already been drawn on your canvas.

There are a total of eleven total GCOs at your disposal. There used to be an even dozen, but the black sheep of the bunch – darker – has unfortunately been abandoned.

In general, you should use source-atop, because it has been the focus of much optimization and is relatively fast. However, there are times when the scene you’re trying to create is difficult or impossible to pull off with source-atop alone.

The GCO modes apply to every pixel that goes onto the canvas. Whether drawn via fillRect, stroke, drawImage, fillText, or anything else – they are all subject to the active GCO. Happily, as the GCO is set on the canvas context, it is subject to the same save/restore (push/pop) behavior as all the other contextual fields (scale, rotation, fill style, global alpha, etc).

This article will explore two of the lesser known GCOs – source-atop and destination-out – and show how they can help you solve some common problems in game graphics programming.

Subtractive Drawing with destination-out

A recent problem I faced was the display of a number of control points on a strategic map. Each point provides a circular “radar” area of effect, and I wanted to depict this area visually so it was obvious to the player which areas were under the effect, and which were not.

The obvious choice to illustrate the radar area border is a simple line – a colored ring around each control point. This is very easy to do with canvas: create a few paths with the .arc() method, and stroke each one.

Blog called Physics in JavaScript

My name is Burak Kanber. I started programming in 1999 and built my first MMORPG in Perl in 2001. Years later I attended the prestigious (and tuition-free) Cooper Union, where I studied automotive and sustainable engineering. I earned my master’s in engineering simulating physics in the powertrain of hybrid cars. I’m presently an entrepreneur and the co-founder/CTO of Tidal Labs, which is proving that you can do awesome things as a bootstrapped startup in NYC. I love teaching (which I do often), and I still love physics. I scratched both of those itches by starting a series on my blog called Physics in JavaScript.

Eventually, Build New Games asked me to write an article on physics for video games. Game development is only a hobby – not my profession – so I did the only sensible thing and started building a legitimate physics engine in native JavaScript as research.

This article will guide you through the essential physics of game engines. This is not an A-Z “how-to” guide. I’ve left out some major optimization and implementation details; a single article can only cover so much. My true goal is to point you in the right direction and teach the concepts that you’ll need to build upon later. The next step is up to you. I hope you’ll use this article as a springboard and go write your own game engine, researching advanced concepts in the process.

I’ve left you a very helpful to-do list at the end of this article, if you’re just here looking for a summary of what you need to learn.

A Vector State of Mind

The first thing I learned when building my physics engine is that you really should embrace vector mathematics (linear algebra). I can already hear you groaning. For some reason, linear algebra always elicits a visceral reaction from people, but please allow me the opportunity to sway you.

Newton’s equations of motion – which dictate basically everything we’re about to do – have a very helpful mathematical quality. You can separate the equations of motion into smaller equations: one each for the x, y, and z axes.

What this means is that when you throw a baseball (in 2D, for argument’s sake) you can solve two separate equations for how it moves vertically and how it moves horizontally. When you throw a baseball, it moves forward at a constant velocity. But it also moves vertically at the same time – and its vertical motion is anything but constant, it’s affected by gravity! Newton’s equations allow you to look at these two aspects separately: “the baseball is moving forward at 90 mph but it’s also moving up and down like so under the influence of gravity”.

For many people, that’s how physics goes. You can just solve each dimension (forward and vertical motion) separately. But I’d encourage you not to do that. Why have three equations when you can have one? Sure, getting comfortable with vector math (again, called linear algebra) has a little bit of a steeper learning curve, but I’ve found that its so much better to work with. It’s worth it.

The account statement from his cloud service provider

Steve cradled his pumpkin spice latte as he walked into the office. It had been three weeks since the launch of his HTML5 multiplayer game, and things were going great. As Steve checked his e-mail, he noticed the account statement from his cloud service provider.

“Let’s see here,” Steve muttered to himself. “Virtual server… 100,000 total hours.” Steve knew this was roughly correct, given the statistics they had been gathering. Thinking about the success of the launch, Steve could barely contain his smile. Skimming further down in the statement, Steve froze. All the way at the bottom, nestled between the line for tax and the heading “Bandwidth” was a number that made Steve’s stomach sink as fast as the latte dramatically falling from his hand.

HTML5 games are growing in a strong way. Once Internet Explorer 10 is released, WebSockets will beavailable in all modern desktop browsers. This technology enables serious realtime communications—the keystone to any non-trivial multiplayer action game. But like a snake in tall grass, bandwidth costs can seemingly come from nowhere. In this article, I want to discuss the oft overlooked cost of network bandwidth and techniques for minimizing it.

The “Hidden” Costs of Network Bandwidth is a WebSockets-enabled networking module for node.js I commonly see recommended for its ease of use, robust fallback support, and integrated publish-subscribe pattern. Here is a snippet of server code that demonstrates this.

In just a few short lines, you have a WebSockets implementation that will fallback gracefully into a number of transports at runtime, on a per-client basis. To see the publish-subscribe pattern in action, let’s look at a sample of client code.

The event system used here is familiar to most people, as it is actually EventEmitter found in node.js. All these things are great, so what’s the issue here and what can this small example reveal about why Steve’s bandwidth bill is so high?

JSON: Strengths and Weaknesses

JSON is a way of representing structured data that has enjoyed native implementations of encoding and decoding in all modern browsers. For many reasons, JSON has picked up acceptance on the web for data serialization. If we examine source, we see that our calls to emit eventually serialize to JSON. Then, supposing we inspect the WebSocket frames, we might see the following.

Physics Engines Comparison

In this article we will take a look at three popular Javascript physics libraries and one that is currently in development: box2dweb, Ammo.js, JigLibJS, and Cannon.js. For each one, a quick introduction will be given and then the library will be rated based on ease of use, performance, and feature set.

Though it is possible to run any of these libraries without a visual representation, that isn’t much fun, so we will set up a small environment to see the results as the simulation runs. I’ll use Three.js and its CanvasRenderer for this due to its popularity and how simple it is to use. Besides showing how the objects are interacting, this will also demonstrate how to extract scene information from each library. The scene will consist of two ramps leading down to a floor; balls will drop down onto the ramps from random locations above the scene, roll down the ramps, and land onto the floor.


Our base scene that will be used in each example has two ramps which lead down to the ground. Balls will be dropped from random points above the ramps, rolling down to and then off of the ground plane. This simple scene will highlight the similarities and differences between the four libraries.

box2dweb is a port of the C++ box2d project and is unique on our list of libraries in that it is designed to only simulate two-dimensional scenes. All of its classes are namespaced which can make the code a little hard to read, so it is recommended that you create your own local variables for any objects you commonly use. Don’t be fooled into thinking box2dweb is a weak library because it only performs 2D simulations; within its simple API is a ton of power. box2dweb has a full constraint system (which it calls joints), continuous collision detection for more accurate fast-moving bodies, and lots of configuration options both for the whole scene and for individual objects.

Collision detection with box2dweb is easy to do by using the b2ContactListener object. You can have separate event handlers for each of the four collision states: BeginContactEndContactPreSolve, and PostSolve. You can also detect collisions by iterating over the world’s contact list after each step.

Intuitive Player Character Movement

Recently, I released Empty Black, my 2D shooter/puzzler/platformer. In this article, I’ll describe how I made the player movement deft and intuitive. Play the game before you read on, so you’ll know what I’m talking about.

My general approach was to change something, then try it out. I took the ideas for adjustments from several sources.

One. I examined the parameters affecting the movement of the player characters in other 2D platformers. Is the floor slippy? What is the ratio of sideways movement to jump height? Does the character accelerate as it moves? Is the character’s jump height affected by the length of time the player holds the jump button? Is the character slowed when it bumps into a moveable object?

Two. I examined the unusual behaviours of the player characters in other 2D platformers. Super Meat Boy makes the character leap away from the wall automatically when wall-jumping. Spelunky lets the character pull himself up and over ledges. In Castlevania, the character can do an extra jump while in mid-air.

Three. I got people to play test. Kemal told me that the character movement should be effortless. Specifically, if the character hits a wall near the top, it should slip up and over. Ricky told me it was weird that the player had no control over the height of the character’s jump. He showed me how, when hopping over an obstacle in a room with a low ceiling, he bumped his head. Ricky also pointed out the jarring effect of the initial slow down of the character when it lands after a jump. Everyone told me that airborne movement was too sensitive. Everyone told me that wall-jumping was too finicky.

Four. I read pieces written by programmers about their character movement algorithms. These pieces were mostly confined to short comments, rather than in-depth analyses. Hence, this article.

To the algorithm.

The short version: a pile of hacks.

The long version:

The player presses the jump key. The first question is: can the character jump? Which means: is the character in contact with anything that can be used as a place to jump from?

Empty Black uses Box2D to control the physics of the game world. Any movements are subject to Box2D’s models of the forces of friction and gravity. Further, Box2D handles the reactions of objects that collide: bounces, shoves, spins and slides. The game can interrogate Box2D and ask what objects a particular object is touching. If the character is currently touching something solid, the character may jump.

Except, it’s not quite that simple. As well as leaping from the ground, the character can wall-jump. This means landing and clinging onto a wall, then jumping again, away from the wall.

Systems From the Ground Up

When it comes to creating games, I am more comfortable slinging code around than creating the visuals. I am always interested in techniques that fall within my comfort zone yet boost my game’s graphical umph. Particle systems are one such technique. By creating a small physics system that throws around hundreds – even thousands – of tiny little particles, awesome visual effects like smoke, fire, sparks, rocket exhaust and many more can be created. They are simple to create and really add nice visual effects to your game. Not to mention particle systems can be given physical properties and participate in your gameplay. In this article we’re going to walk through many of the details and considerations in a typical 2D particle system.

Above is a particle system configured to look like a meteor. You can pick from several other particle systems from the dropdown as well. In all cases the same engine is driving the particle systems, just using a different configuration each time. It’s pretty nice that one system can produce such a variety of visual effects!

Despite their slightly intimidating name, particle systems are very common these days and simple in concept. Most game engines have particle systems baked in. Unfortunately for HTML5 game engines, this often isn’t the case. This is partly due to most HTML5 game engines being a bit on the young side, but also and due to the fact that historically canvas has not been performant enough. In modern browsers, canvas’s performance has improved quite a bit, and adding particle effects to your HTML5 game is pretty doable (but there are performance considerations, see the performance section below). Even if your favorite engine of choice doesn’t include built in support, it’s easy to roll your own. We’ll start with a very naive system that gets the basics down, then talk about more interesting features that are commonly found.

A quick note, the particle system engine used throughout the article is heavily inspired by Cocos2D’s particle system implementation. Even the above examples should look pretty familiar to Cocos2D users. I thought due to Cocos2D’s popularity, it made sense to follow closely to what they’ve done. So a quick shout out to Cocos2D, thanks guys!

A Naive Particle System

To begin our simple particle system, let’s define a Particle type. We need to know where the particle is and where it’s headed; in this respect, a particle is not much different from any other entity in a game. We also want each particle to only live for a certain amount of time. So with that in mind we can start out with:

Nothing too exciting going on here, but it’s worth pointing out that the constructor takes an angle (in degrees) and a speed (in pixels per second) and converts these values into a velocity vector. This is intentional, when setting a particle up it’s easier to work with an angle and a speed. But when updating the particle each frame, it’s easier to work with a velocity vector.

Reacting to each other realistically

One of the most complicated and math-intensive components of game development is collision detection and response. If all you need is to calculate when a couple of rectangles overlap, it’s not a big deal, but for games that involve lots of irregularly shaped sprites moving and reacting to each other realistically, you’ll want to use an industrial strength tool to get the job done.

Enter the physics engine.

The idea behind using a physics engine in your game is that instead of hacking together a very-loose approximation of how real objects might interact for your game, dropping in an engine whose sole purpose is to run the physics simulation allows you to leave it to the engine to handle object dynamics and interactions and concentrate on the game itself.

To this end a number of different Physics engines, both 2D and 3D have made their way to JavaScript, many of them ports from other languages, but some written from scratch. For an overview of a number of different engines, take a look at Chandler Prall’s JavaScript Physics Engine Comparison.

Of the myriad of open-source 2D engines that are available, one stands out: Box2D. One reason for this is that it was used as the simulation engine behind mega-hit Angry birds, whose physics-based gameplay required a bullet-proof physics implementation. Box2D is the 2D physics engine of choice for many games, and thus was ported wholesale over to Flash and ActionScript a while back. To get a JavaScript version, some ambitious folks have taken advantage of the similarities between ActionScript and JavaScript and created a converter that converted the ActionScript to JavaScript.

There are a few ports floating about, but the most popular one is Box2DWeb:

Some work has also been done to convert directly from C++ to JavaScript using emscripten (See box2d.js) but this has a different API than box2dweb and doesn’t appear to be kept up.

Box2DWeb doesn’t have it’s own documentation per se, but it shares the same API as the Flash library it was converted from, so the Box2DFlash Documention can be used to figure out the Box2DWeb API. If you’re interested in really diving into Box2D, the official Box2D C++ manual also makes for a worthwhile read, although it contains some newer features not found in Box2DWeb.