Resources - Local Storage and Multiplayer Games - HTML5 Games: Creating Fun with HTML5, CSS3, and WebGL (2012)

HTML5 Games: Creating Fun with HTML5, CSS3, and WebGL (2012)

part 4

Local Storage and Multiplayer Games

Chapter 14


in this chapter

• Using game engines and other middleware

• Deploying on mobile devices

• Distributing your games

• Enhancing your game with online services

• Getting the word out

In this book, I have mostly demonstrated the low-level aspects illustrating how you can use HTML5 to create games. It’s important to have an understanding of the lower levels of the technology you’re using, but it’s also important to know when not to reinvent the wheel. The first part of this chapter discusses middleware solutions that can make your life easier when implementing physics simulation, WebGL graphics, and games in general.

You also have several options for distributing your finished games without dealing with the logistics yourself. Mobile platforms, such as Android and iOS, have well-developed distribution channels in the form of Apple’s App Store and Google’s Android Market. These channels are only for native applications, however, but there are ways to get around that. In this chapter, I also show you a few services and tools you can use either to package your game as a native application or to use your web development skills to develop true native applications.

I also introduce you to a couple of services you can use to host your games as well as enhance them with features such as online leader boards, statistics, and achievements.

Using Middleware

Creating a game from scratch can be a daunting task, especially for a lone developer. If you are interested in experimenting with the nitty-gritty details of the technology, the process of building the foundation can be just as rewarding as implementing the game on top. If you are more concerned with building the actual game rather than the building blocks, a little help can make the process more manageable. In this section, I introduce you to a few middleware projects that can help you by taking care of the low-level details while letting you focus on creating the game.


Not all games require physics simulation. Sometimes physics simply doesn’t play a role in the game. Other times, implementing the needed physics is trivial. However, when the game does call for a more advanced simulation of physics, middleware such as a good physics engine can save you lots of time.

Box2D aims at providing stable simulation of classical mechanics such as forces, impulse, friction, joints, and constraints. It also sports advanced collision detection and has stable stacking. The engine has been used in many games on various platforms. Notable examples include the hit games Angry Birds and Crayon Physics Deluxe.

The original Box2D ( was written in C++, but it has since been ported to many other languages including a few JavaScript ports. The first JavaScript port was the Box2DJS project (, which is based on the Flash port Box2DFlashAS3 ( Unfortunately, Box2DJS uses an old version of the Flash port, and not all features are completely ported. It also requires the Prototype library, which you may or may not like. Another port of the Flash version, box2d2-js, is based on the latest version of Box2DFlashAS3 and is still actively maintained by its author, Jonas Wagner. You can find his version at

The code in Listing 14.1 shows a simple example of how to use box2d2-js to set up a 2D world on a canvas element that spawns falling circles when the user clicks the mouse. You can find this example in the file 01-box2d.html in the code archive for this chapter.

Listing 14.1 Falling Balls with box2d2-js

var canvas = document.getElementById(“canvas”),

ctx = canvas.getContext(‘2d’),

rect = canvas.getBoundingClientRect(),

lastTime =,

worldAABB = new b2AABB(),

world = new b2World(worldAABB, new b2Vec2(0,9.8*10), true);

worldAABB.upperBound.Set(1000, 1000);

canvas.addEventListener(“click”, function(e) {

var shape = new b2CircleDef(),

body = world.CreateBody(new b2BodyDef());

shape.radius = 10;

shape.restitution = 0.5;

shape.density = 1.0;

shape.friction = 0.95;




new b2Vec2((Math.random()-0.5) * 100, 0)


body.SetXForm(new b2Vec2(

e.clientX - rect.left, e.clientY -

), 0);

}, false);

function cycle(time) {


world.Step((time - lastTime) / 1000, 10);

lastTime = time;


for (var b = world.GetBodyList(); b; b = b.GetNext()) {

if (b.IsStatic() || b.IsFrozen()) continue;


ctx.arc(b.GetPosition().x, b.GetPosition().y,

10, 0, Math.PI * 2, true






As the name implies, Box2D is meant for two-dimensional physics. If you are making a 3D game, you have to consider other options. A few 3D physics engines do exist, but they do not appear to be as fully developed as Box2D. For one of the more promising projects, check out JigLibJS2 at


The Impact game engine (, developed by Dominic Szablewski, is perhaps the most promising JavaScript game engine I’ve seen so far, at least when it comes to creating 2D games. Dominic used the engine to create his game Biolab Disaster (, an impressive 2D platform game that demonstrates many aspects of the engine. The engine was also featured in the May 2011 edition of Game Developer magazine, further underlining both the quality of Impact and the promising future of HTML5 as a game development platform. Games built with Impact run on desktop browsers, Android devices, and iOS devices such as iPhone and iPad.

The engine costs $99 to use, which may put off some people, considering there is no trial version. The license is per developer, but because it can be used for an unlimited number of games, you need to pay this fee only once.

Impact comes with a few simple demo games and video tutorials that demonstrate how to use the level editor and how to create a Pong-like game. The engine documentation, which you can find on the web site, is nice and detailed and includes both practical examples for several key topics and an API reference. To further aid you in the development phase, Impact has an integrated debug panel that shows game entities and performance analysis. You can easily toggle the debug mode on and off so the panel is visible only when you’re working on the game.

The Impact engine includes a level editor called Weltmeister that you can use to construct 2D levels for your games. The level editor is built with HTML and JavaScript but uses a PHP-based back end, so you need access to a PHP-capable server to be able to use this tool. The same goes for the included scripts that you can use to build everything to a single JavaScript file. Other than a web server running PHP, you don’t need any extra tools to start developing with Impact.

Developing with Impact is straightforward and intuitive when you get the hang of it. The engine is modular, and most of the modules that you add extend existing classes. Listing 14.2 shows what a module for a player character could look like. You can find this code in the file 02-impact.js.

Listing 14.2 Defining a Player Character Entity








EntityPlayer = ig.Entity.extend({

// load sprite sheet with 32x32 sprite images

animSheet: new ig.AnimationSheet(

“images/player.png”, 32, 32


// enable passive collision

collides: ig.Entity.COLLIDES.PASSIVE,

// add a few animations, 0.5 seconds per frame

init: function(x, y, settings) {

this.parent(x, y, settings);

this.addAnim(“idle”, 0.5, [0]);

this.addAnim(“moveleft”, 0.5, [1,2]);

this.addAnim(“moveright”, 0.5, [3,4]);


// if left or right is pressed, move character

update: function() {

if (ig.input.state(“left”)) {

this.currentAnim = this.anims[“moveleft”];

this.vel.x = -50;

} else if (ig.input.state(“right”)) {

this.currentAnim = this.anims[“moveright”];

this.vel.x = 50;

} else {

this.currentAnim = this.anims[“idle”];

this.vel.x = 0





That’s all the logic it takes to set up a player character with horizontal movement. The Entity class that this EntityPlayer extends is one of the most important classes in Impact. Every object present in the game world inherits from Entity. The init() function sets up a few animations generated from the animation sheet. The animation sheet is essentially a long image file with all the frames of the animation placed next to each other.

You can easily integrate Box2D with Impact to add physics to your game. Although Impact doesn’t have Box2D functionality out of the box, you can find an example using Box2D in the download section of the web site. Note that the download section is accessible only if you have a license key. If you haven’t paid for a license, you can still try the physics demo at


With WebGL getting more and more attention, it follows naturally that middleware for this particular technology is also popping up. Considering the relatively young age of WebGL, a surprising number of 3D engines and libraries are based on WebGL. One is Three.js by Ricardo Cabello, aka Mr. Doob. Three.js takes away a lot of the complexity of working with WebGL, and the road from blank page to a basic 3D scene can be very short. Listing 14.3 shows the code necessary to render a rotating sphere. You can find this example in the file 03-threejs.html.

Listing 14.3 A Basic Three.js Example

var canvas = document.getElementById(“scene”),

camera = new THREE.Camera(

60, canvas.width / canvas.height, 1, 10000


scene = new THREE.Scene(),

renderer = new THREE.WebGLRenderer({ canvas : canvas }),

mesh = new THREE.Mesh(

new THREE.SphereGeometry(300, 20, 10),

new THREE.MeshPhongMaterial(

{ color: 0x00dddd, shading : THREE.FlatShading})


light = new THREE.DirectionalLight(0xffffff, 1.2);

camera.position.set(0, 0, 1000);

light.position.set(500, 500, 1000);



function render() {


mesh.rotation.set(0.3, / 800, 0);

renderer.render( scene, camera );



Quite the difference from the elaborate code from Chapter 11. Three.js takes care of setting up buffer objects and shaders, leaving a much simpler interface for you to work with. Despite the simplified rendering flow, Three.js has been used in some very intricate projects; for example, interactive music experiences for artists such as Danger Mouse ( and Arcade Fire (

Three.js includes a number of built-in primitives that you can generate, such as cubes, spheres, and cylinders. It doesn’t have functionality for loading external model files, but you can get around that limitation with a few tricks. If you export your models from your 3D graphics package to Wavefront OBJ format, you can convert them to a custom JavaScript format with a small utility included in the Three.js package. OBJ is a common 3D file format supported by many popular 3D graphics applications such as Blender. The converter is written in Python, so you need to have Python installed to import these models. You can load the JavaScript file produced by the converter directly into Three.js.

Three.js doesn’t just stick to pure graphics, though. You can also place sound emitters in the 3D environment and have them play sounds. Three.js then automatically adjusts the volume and left/right balance based on the player’s position.

In addition to WebGL, Three.js can also render the 3D content to a regular, 2D canvas element or to an SVG element. That requires that you dial down the complexity of your scenes because both performance and features are limited without WebGL.

One area that leaves a bit to be desired is the documentation. The Github project page ( has only a very brief example, a terse API reference, and a link to a third-party guide (, should you want a gentler introduction to the engine. However, the project archive available from the Github project page contains more than a hundred examples that you can learn from, ranging from very simple to quite advanced. On the project page, you can find even more user-contributed examples that demonstrate advanced features such as reflective materials, normal mapping, and particle effects. Learning Three.js ( is another interesting site that is still relatively new but looks very promising.

Three.js is free, and the code is licensed under the MIT license.

Deploying on Mobile Devices

Being able to develop iOS and Android applications with the tools and techniques you already know is great, but you also miss out on some of the opportunities available to native application developers. Two key elements available only to native applications are access to the native APIs and the opportunity to publish through the App Store and Android Market. Fortunately, you can do some things that at least get you some of the way. This section describes two solutions to the question of how to make your web application behave like a native mobile application.


The first solution is PhoneGap by Nitobi ( PhoneGap aims to bridge the gap between native and web by wrapping your web application in a native application. It does so by using the native web view control to render your game or application, which means that your game or application will render just as if it ran in the mobile browser, only without the browser’s UI. In fact, no native UI is present at all. Any interface controls you need in your application, you must create with HTML and CSS.

PhoneGap can build applications for several mobile platforms besides Android and iOS. The full list of supported systems is

• iOS

• Android

• WebOS

• BlackBerry WebWorks

• Symbian

• Bada

• Windows Phone 7

Depending on which platforms you want to use, you need to do a bit of work to set up your development environment. To build Android applications, you need the Android SDK ( and Eclipse Classic ( Eclipse runs on Windows, Linux, and Mac OS X. You don’t get the same freedom if you want to build your game for iOS because you need a machine running Mac OS X and the Xcode development suite ( You also need to enroll in the iOS Developer Program ( to be able to install your game on the actual devices and to distribute it through the App Store. Enrolling is easy but costs $99 per year.

You can then download the PhoneGap package, which contains a folder for each target containing the necessary files. You can find the full instructions for how to set up Eclipse and Xcode projects at the PhoneGap web site.

When your web application is executed via PhoneGap, you can do most of the things that you can do in the proper mobile browser. There are limitations, however, and some things are still being worked on. The current version, 1.0, has no support for WebSockets or the audio element, for example, although both are planned for future releases. PhoneGap supplies its own media API that you can use until the standards-compliant media elements are implemented.

The media API is far from the only extra API available to you. One huge advantage PhoneGap has over regular web applications is that it exposes several native APIs through a JavaScript interface. The exposed functionality includes

• Accelerometer

• Camera and AV capture

• Wi-Fi and cellular connection

• Geolocation and compass

• Native notifications

• File system access

You can find even more functionality in the plug-ins available from the PhoneGap Github repository (

Not all platforms support all the APIs, though. Check the documentation ( to see where each feature is supported. To use these native features, you simply include the PhoneGap JavaScript file in your project. Of course, the functions do not work correctly until the application runs on the actual device. Listing 14.4 shows a basic example of how to use the PhoneGap camera API to take a picture. The code for this example can be found in the file 04-phonegap.html.

Listing 14.4 Taking a Picture with PhoneGap


<html lang=”en-US”>


<meta charset=”UTF-8”>

<script src=”phonegap.js”></script>



<button id=”snap”>Take a picture!</button>


var button = document.getElementById(”snap”);

button.addEventListener(”click”, function() {

function(data) {

var img = new Image();

img.src = ”data:image/jpeg;base64,” + data;


}, function(errMessage) {

alert(”Camera error: ” + errMessage);

}, {

quality : 70



}, false);




PhoneGap is free, and the code is dual-licensed under the MIT and BSD licenses. The dual license means that you are free to pick whichever of those licenses you want to adhere to. They are both permissive and place almost no restrictions on what you can do.

Although Nitobi created PhoneGap, it received many contributions from third parties, including big players such as IBM. Adobe, too, has shown interest and has been making a push toward mobile devices and iOS in particular, perhaps as a response to Apple’s refusal to add Flash support to iOS. Adobe Flash Professional and AIR now both export to iOS, and Dreamweaver leverages PhoneGap to deliver web applications on iOS and Android.

Although PhoneGap is great in itself, what makes it really stand out in my mind is the PhoneGap Build service ( With PhoneGap Build, you can upload an archive file containing all your project files, and PhoneGap Build then automatically builds Android and iOS applications, ready to download. You can also set up a Git repository — for example — on Github, and have PhoneGap Build pull the files from there. That makes the whole process of creating native applications very smooth.

Developing applications locally for iOS and Android requires that you set up the necessary tools and, in the case of iOS, that you are using Mac OS X. PhoneGap Build lets you build native iOS and Android applications with as little hassle as possible at the price of some flexibility. If you want to have full control over the build process, you must install the development tools yourself.

The archive file that you upload to PhoneGap Build can contain an XML configuration file that specifies metadata about the application. Listing 14.5 shows an example of such a file.

Listing 14.5 Sample config.xml File

<?xml version=”1.0” encoding=”UTF-8”?>

<widget xmlns = “”

xmlns:gap = “”

id = “com.phonegap.jewelwarrior”

version = “1.0.0”>

<name>Jewel Warrior</name>


A game of jewel swapping


<author href=””


Jacob Seidelin


<icon src=”favicon128.png” gap:role=”default” />


<gap:platform name=”android” minVersion=”2.1” />


<feature name=””/>


This example can be found in the file 05-config.xml. You can add more elements and settings to the configuration file, but these are some of the most important. The platform nodes specify which platforms you want to build for. Note that you can specify the minimum version for the target OS if your application works only on newer versions. The feature nodes list all the extra privileges your game needs to be able to run. In this example, the application requests access only to the media API. Not all the PhoneGap APIs are available via the Build service, however. See the help pages on the PhoneGap Build site for an up-to-date list of the supported APIs.

In my tests, I found that a ZIP archive of the Jewel Warrior files built without problems and the Android application worked out of the box. Even if you don’t take advantage of the extra features available from the PhoneGap API, the Build service is very useful and easy to work with. Building iOS applications still requires an iOS Developer license, of course, and you need to set up your signing key with PhoneGap Build before being able to build iOS applications.

Appcelerator Titanium

Appcelerator’s Titanium is another project that lets you use your existing web development skills to build native applications for Android, iOS, and other mobile platforms. The project started off as something similar to PhoneGap with applications built entirely with HTML, CSS, and JavaScript. It has since shifted its focus toward a more native-oriented direction but still retains some of its web roots.

Titanium lets you build native applications and games in a fully integrated development environment (IDE) using JavaScript as the main language. Titanium no longer relies on HTML and CSS but instead provides a detailed API for you to use. Because you presumably already know JavaScript, Titanium makes it easier to develop native applications, as it no longer requires Java or Objective C skills.

Titanium Studio, the IDE provided by Appcelerator, is based on Aptana Studio, an Eclipse-based web development IDE. The software is available on Windows, Linux, and Mac OS X. Your applications and games can be built for several mobile platforms, including iOS, Android, and Blackberry (currently in beta). You do need to have the development kits installed for the various platforms, though. That means Java Development Kit and the Android SDK ( for Android applications and Xcode and the iOS SDK for iOS builds. As with PhoneGap, you also need an Android Market publisher account ( and an iOS developer license ( to deploy the final product on the devices.

Being able to turn your web application into a native application is great, but it can be difficult to shake the web feeling completely without the native UI controls. Most users expect the interface to behave in a certain way and are very sensitive to small differences in the experience. On top of that, web-based user interfaces can often seem a little sluggish compared to their native counterparts. In contrast, Titanium uses the native UI controls and exposes them through a JavaScript API. This means that your application will enjoy both the look and feel as well as the performance of a native application. This is surely a good thing, but the move from HTML and CSS to the code-based Titanium approach can be a little hard to get used to. Note that it is still possible to create a web view control and use it to display normal web content.

Similar to PhoneGap, Titanium exposes a number of native features to your application. Some of the available features are

• Accelerometer

• File system and database

• Contacts and Facebook

• Network

• Geolocation

Titanium is free to use in the basic edition. You can get access to extra features such as OpenGL on iOS if you upgrade to one of the paid subscriptions. The smallest subscription, the Indie plan, is currently $49 per month and gives you access to the premium mobile APIs as well as extra training videos.

Distributing Your Games

Whether you create a native application or stick to the pure web format, you need to get your game out there. This section discusses some of the options available to you when you need to distribute your game to your potential users.

Chrome Web Store

The Chrome Web Store ( is Google’s shot at creating an online distribution channel for web applications. As the name implies, the Chrome Web Store is aimed at Chrome users. If you visit the store with any other browser, you’re asked to download and install Chrome. Given the content of the store, this makes sense because all the applications can be installed as Chrome Web Apps that appear on the user’s startup page. Also available are extensions and themes for Chrome.

You need a Google account to get your application or game published in the Chrome Web Store. You also need to pay a one-time $5 registration fee when you publish your first application. After that, there are no charges for using the service.

After you sign up, you can start uploading applications. The project files must be uploaded as a ZIP archive containing the project directory. You also need to create a manifest file and a set of icons and include them in the archive. Packaging your game as a Chrome Web App gives you a few extra benefits because these applications receive the same privileges as Chrome extensions. That means your application can perform cross-origin XMLHttpRequests, access bookmarks and browser history, manage tabs and windows, and perform several other tasks.

The manifest is a relatively simple JSON file that declares, for example, application name, description, and version. The manifest must be placed in the root of the project directory and named manifest.json. Listing 14.6 shows an example of a manifest. You can find the example in the file06-manifest.json.

Listing 14.6 A Sample Manifest for a Chrome Application


“name”: “Jewel Warrior”,

“description”: “Swap jewels for great justice!”,

“version”: “1.0”,

“app”: {

“launch”: {

“local_path”: “index.html”



“icons”: {

“16”: “icon_16.png”,

“48”: “icon_48.png”,

“128”: “icon_128.png”


“permissions”: [






Most of the settings in the manifest should be self-explanatory. The permissions property is a list of the special privileges the application needs. In this example, the application needs access to tabs and windows, it requires unlimited storage space, and it must be able to make cross-origin HTTP requests to the domain. You can find more information about the manifest and packaged applications in general in the Developer Guide (


Zeewe ( is a relatively new service that lets you market your applications to mobile users. It wants to be for web applications what App Store and Android Market are for native applications. Zeewe targets only iPhone/iPod touch, iPad, and Android devices. You are not able to access the applications from a desktop browser.

The store itself is, unsurprisingly, also a web application. The interface, which was built with jQuery Mobile, feels very slick and is a good example of what you can do with HTML5 in terms of delivering native-feeling experiences on mobile devices. On iOS devices, the store can be installed on the home screen, so it can be launched like any native application. On Android, the store is presented directly in the browser.

To get your application or game featured in the Zeewe store, you simply submit the details via a simple form ( You get to choose on which platforms the game is available (Android and/or iOS), and you can upload screenshots and enter descriptions and other metadata. Zeewe doesn’t offer application hosting, so you need your own web host to be able to use the store. Zeewe does, however, provide several services that you can use to enhance your games. These services are available via a JSON API and include high scores, logging, notifications, and a payment system that you can use to implement in-app purchases in your games.

My current experience with Zeewe is that it is a bit rough around the edges and still needs a bit of work. The “beta” label on the logo also indicates that the team is still actively developing the service. It looks very promising, however, and is definitely a site to watch out for as it matures.

Android Market

The Android Market ( is the most popular distribution channel for distributing applications for Android devices. If you’ve made a game that is suitable for handheld devices, you should definitely consider making it available via Android Market to make it easier for the average Android user to find the game. Android Market is only for native Android applications built with the Android SDK, but if you use either PhoneGap or Appcelerator Titanium to create an Android Package (APK) file and otherwise stick to the Android content guidelines, you should have no problem getting it accepted.

You publish your applications and games at the Android Market Publisher site ( If you don’t already have one, you need to sign up for a free Google account before you can sign up as an Android publisher. Although Google accounts are free, you need to pay a $25 registration fee via Google Checkout to access the Android Market publisher site. If you want to sell your games, you also need a Merchant’s account on Google Checkout to be able to receive payments. If you plan on publishing only free applications, a regular account works fine.

Publishing applications is fairly simple when you have a correctly signed APK file. You can find information about how to sign your applications in the Developer’s Guide (

App Store

App Store is for iDevices what Android Market is for Android devices. The App Store is strictly for native iOS applications and lets only licensed developers publish their applications and games.

To develop iOS applications, you need to sign up for an iOS developer account ( Before you can sell your applications through the App Store, you must also enroll in the iOS Developer Program. This program carries an annual $99 fee and gives you access to beta software, a large number of guides and other resources, as well as the key needed to sign your applications. Activating your account can take up to 24 hours.

Initially, a bit of confusion surrounded iOS applications made with tools such as PhoneGap due to Apple’s strict policies regarding how and where iOS development can take place. Eventually, Apple responded and gave the green light, so PhoneGap and Titanium applications should have no trouble being accepted.

You do need, however, to be aware of Apple’s often criticized and sometimes obscure acceptance criteria. All submitted applications go through a review process, and many applications have been rejected based on what seems like arbitrary arguments. In Apple’s defense, the company has taken steps to make the process more transparent. You can find the approval guidelines at

Using Online Services

The middleware discussed in the first part of this chapter were all things you had to download and integrate locally as a part of your game. I now go through some services that exist only online and let you add features that would otherwise require you maintain a server and write server-side code.


If you need a place to host your game, you should look at TapJS (, which specializes in hosting web games. TapJS accepts only games made with HTML, CSS, and JavaScript and serves your game to desktop, iOS, and Android devices.

After you upload your game, it is available via a * subdomain of your choosing; alternatively, you can use your own domain name and point it to an IP address provided to you in your TapJS dashboard. Besides hosting your game, TapJS also can add high scores and a comment feature to the game. Badges are another cool game enhancement. Players earn badges by accomplishing certain tasks in the game, similar to the achievements and trophies known from, for example, gaming consoles.

TapJS ties into a few external services, too. If you use Google Analytics, you can connect your TapJS-hosted game to your Analytics account to take advantage of Google’s advanced metrics. If you want to reach out to the millions of people who use Facebook for casual gaming, TapJS helps you there also. Create a fresh Facebook application by following the guide at the Facebook developer site ( and then enter the application details in the Facebook section in TapJS as described in the TapJS documentation ( Your TapJS-hosted game is then automatically available through Facebook.

TapJS makes a demo game available at that demonstrates how your game is presented. The game was made with Dominic Szablewski’s Impact engine, so it also serves as a demo for Impact as well as how these two projects make use of each other.


Playtomic ( is an interesting service that offers to help you get more insight into how people play your games as well as add features such as leader boards and level sharing. After you sign up and add your game to your account, you need to download a JavaScript API and include it in your project. This API provides all the functionality you need to make your game communicate with the Playtomic servers.

Playtomic offers several different services, many of them related to analytics and metrics. Some of the most obvious ones include graphs showing number of plays and time spent in your games as well as traditional web metrics. Heat maps give you visual maps of the busiest areas of your game interface. Level metrics are an interesting service that can help you identify troublesome levels.

If the metrics offered by Playtomic are not enough, you also have the option of creating customized metrics using your own variables. You can even set up custom databases to create your own game features such as saved games or messaging systems. Another use for this capability would be high score lists and leader boards, but Playtomic actually offers a leader boards feature that you can use to rank players.

Signing up is free, and adding your game takes only a few minutes. The API script is provided as is, and you are free to modify it as you like, should you want to add new features or modify the existing code. The API documentation ( is pretty solid and provides detailed descriptions of all the functions.

Getting started with Playtomic is easy. First, include the API script, which is hosted on Playtomic’s servers:

<script src=””>


The script gives you access to the Playtomic API, which you then need to initialize with credentials that you receive when you add the game to your account:

Playtomic.Log.View(gameid, guid, apikey, document.location);

That’s it — you can now use all the Playtomic functions in your game. The following snippet uses the geolocation service to identify the player’s country:

Playtomic.GeoIP.Lookup(function(country, response) {

if (response.Success) {

alert(“Hi! You are from “ + country.Name);

} else {

// something went wrong



Aside from providing services to HTML5 games, the Playtomic service is also available for Flash and Unity games as well as native iOS games.

JoyentCloud Node

One of the most talked about JavaScript-related projects over the past year or two has been Node.js (, a relatively new JavaScript-based server environment. Node.js is based on the V8 JavaScript engine that also powers the Chrome browser. Instead of using JavaScript for client-side scripting, Node.js uses JavaScript and its inherent, asynchronous event-based nature to create a very efficient environment for writing server code. If you are thinking of adding server-side features or perhaps even multiplayer features, taking a good look at Node.js is a good idea. Node.js comes with many built-in modules, and users and developers around the world have made many more available, enabling features such as WebSockets in a few lines of code.

If you do use Node.js to add multiplayer and other server-side features to your games, you, of course, need a hosting solution capable of running Node. If you don’t have your own server and your current hosting doesn’t provide Node, the Node SmartMachines ( provided by Joyent is a great alternative.

SmartMachines are accessible via a public IP address and a self-chosen * subdomain. Before you can access the machine, you must set up SSH keys to establish secure connections. Don’t worry if you are not familiar with SSH keys; you can read more about keys and how to create them in the Help section on the JoyentCloud web site ( The Joyent staff is also very friendly and happy to help if the service gives you trouble.


This final chapter introduced a number of projects, tools, and services that you can use in your future work with HTML5-based game development. You saw how engines such as Box2D, Impact, and Three.js can make game development easier by taking care of the low-level details. You also learned that you are able to get your applications and games onto iOS and Android devices as native applications while still using your existing skill set and avoiding Java and Objective C.

Finally, you learned about a few services that help you enhance your game by hosting it, adding online features such as leader boards and achievements, and adding your own online functionality using the JavaScript-based Node.js.

I hope that you now feel well equipped to begin your own experiments in the world of HTML5 game development. While HTML5, CSS, and other web technologies are still toddlers compared to established languages and frameworks such as Java, C++, OpenGL, and DirectX, I hope you take away the same feeling as I have, that the Web is changing into something new and that good times are ahead for those who embrace it. The best thing about working in this rapidly developing area is that tomorrow there’s always something new to discover, play with, and put to use in even more exciting projects. Good luck—I look forward to playing your games!