Click here to Skip to main content
12,814,249 members (37,615 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


24 bookmarked
Posted 15 Mar 2012

Top 5 Best Practices for Building HTML5 Games…In Action!

, 15 Mar 2012 CPOL
In this article I give you an overview of things you should consider before you write a game using HTML5 and while you’re working on it

Editorial Note

This article is in the Product Showcase section for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers.

HTML5 is great because it’s versatile—it’s not specific to a single use case. More important, HTML5 is ubiquitous. It’s on your PC, your phone, your slate device—for all I know, it could even be on your kitchen appliances.

Take these two properties of HTML5—versatility and ubiquity—and it should become pretty clear why so many developers are inspired by it. And, as the  proverb goes, "When developers are inspired, they usually write games." (Okay, maybe I just made up.)

Fortunately, deep-dive articles on HTML5 game development are now widely available. Instead, I’d like to give you an overview of things you should consider before you write a game using HTML5 and while you’re working on it.

What will you learn in this article? I’ll cover HTML5 game development frameworks, how you can reach more people by supporting smartphones and slate devices, how you should go about managing your in-game state, how to deal with performance issues, and how to make the most of the platform that is your browser.

So without further ado, here are the top 5 best practices for building HTML5 Games, in action! ("in action" added for dramatic effect).

Best practice #1: Use a framework

Writing simple games in HTML5 is easy, but as you up the ante, you need to do certain things to make sure that your game runs smoothly.

For example, when you use a lot of images, sound effects, and other resources, it will take some time for your browser to download it all from your web server. You’re in for a surprise if you don’t take this into account when writing your game. Because images and sound files are loaded asynchronously, your JavaScript code will start executing before all of your resources have been loaded. This often results in "popping" (images appearing out of the blue), and in sound effects not playing when they should. A good fix for this is to create a preloader that defers script execution until all resources have been downloaded.

Another problem you’ll likely run into is that different machines and/or browsers will run your game at different speeds. While there is nothing you can do about that, you should still make sure that animation and movement speeds are independent of the frame rate your game is running at.

Essentially, there’s a LOT of boilerplate code that every game needs in order to function properly. Fortunately, you don’t have to write all of this code yourself. There are now a variety of frameworks that allow you to focus on your game logic without having to worry about all the little (and big) things necessary to make your game run smoothly.

The only caveat with using a framework is that there are so many to choose from. Frameworks like ImpactJS for example are designed to help with almost every aspect of the game development process, while frameworks like EaselJS focus primarily on the graphics side of things. In the end, it’s up to you to pick the framework that you are most comfortable with. This may seem like a no-brainer, but in the JavaScript world, choosing a framework often implies opting into a particular style of programming.


Monster = ig.Entity.extend({
    eyes: 42


A good example of this is ImpactJS, which not only provides abstractions for displaying graphics or playing sound effects but also introduces its own object and inheritance model as illustrated above.

Ascend Arcade delivered three games in three months using the ImpactJS framework.

Although a lot of HTML5 games now rely on some form of framework, many developers still go down the rocky road of trying to do everything themselves. While this might be a great learning experience, if you want to get things done in a reasonable amount of time, using frameworks is definitely the way to go. A good example of this is the great work of Ascended Arcade who managed to release three very enjoyable (and somewhat acclaimed) games in only three months using the ImpactJS framework.

Best practice #2: Consider small- and touch-screen devices

Maybe one of the most persuasive selling points of HTML5 is that it works on desktop PCs, laptop computers, slates and even smartphones (if you haven’t seen IE9 running on Windows Phone 7 Mango, check out this video).

This unique cross-platformness (take that, Webster’s dictionary!) is intrinsic to HTML5 and often requires little additional work from the developer. However, there are a couple of things you should consider…

First and foremost, screen sizes can vary greatly between different device categories as can screen resolutions and aspect ratios. If you want your HTML5 games to work well on mobile devices, you should make sure they either support multiple resolutions or don’t exceed the WVGA frame size of 800x480.

Also, since most mobile devices lack the screen size to render an entire web page at once, they often employ sophisticated zooming and panning techniques that can be counterproductive when writing games. These can be turned off programmatically using the viewport meta tag. The following code snippet will cause your game’s viewport to occupy all of the available horizontal screen real estate. Setting the parameter "user-scaleable" to "no" tells the mobile browser to disable pinch-zooming, which otherwise often conflicts with finger-based game controls.

<meta name="Viewport" 

  content="width=device-width; user-scaleable=no; initial-scale=1.0"

Once your game renders okay on small-screen devices, you should also take a minute to think about input. Most touch-only devices have a virtual keyboard, but they tend to take up too much screen space to be useful in controlling game characters. If strictly touch-based input is out of the question, you should build a limited virtual keyboard with only the buttons you need for your game (e.g. the arrow keys). However, it’s best to be creative with alternative means of controlling your game that don’t require additional on-screen elements. A good example of this is the game Spy Chase, where you drive a vehicle with one finger (something you should not attempt in real life).

Best practice #3: Automatically save the player’s progress

With features like site pinning, web browsers attempt to give web applications the same status as regular desktop applications. However, the idea of websites functioning as applications is rather new, and so is the notion of web pages holding client-side state. You might think twice before closing an instance of Microsoft Word, but you might not be as careful with an open web page. Most of the time, this isn’t a problem—most web pages are either stateless or maintain a record of your information on the server.

Browser games, however, are a slightly different beast. Since JavaScript code is executed on the client, HTML5 games typically keep their game state in transient memory (aka RAM). Close the browser window and your hard-earned highscore is forever lost.

Now, you might argue that a sensible person would be cautious enough not to close the game they’ve been playing for eight hours, but accidents do happen, especially when multiple tabs are involved or batteries run out of juice.

To make a long story short: When writing HTML5 games, it’s an absolute best practice to save the player’s progress regularly and allow players to resume their game when returning to a web page they’d closed.

Now where should you keep track of players’ progress? In the past, the obvious place was either a server-side database or a client-side cookie. Neither solution is especially appealing. With a server-side approach, HTTP requests have to be made whenever information needs to be stored or retrieved. The cookie approach gives you very limited space to work with and the longevity of cookies greatly depends on the browser configuration.

A much more workable solution is to use HTML5 DOM storage. DOM storage lets you save several megabytes of data per website through an interface that resembles a key-value store (or a JavaScript expando object). It’s very convenient, but in the context of HTML5 games, you might also want to remember complex data structures—something that DOM storage does not natively support.

Fortunately, modern JavaScript implementations have mechanisms built in that enable the serialization of objects into a compact notation known as JSON. Using this approach, DOM storage can also be used to remember arbitrary information. The following two helper functions illustrate how game state can be stored and retrieved using HTML5 DOM storage and the JSON features built into ECMAScript5:

function saveState(state) {
	window.localStorage.setItem("gameState", JSON.stringify(state));

function restoreState() {
	var state = window.localStorage.getItem("gameState");
	if (state) {
		return JSON.parse(state);
	} else {
		return null;

Best practice #4: Use a profiler

One of the greatest challenges when developing a game is to maintain high frame rates as you add more and more features to it.

The good news is that browsers in general have become much faster over the last couple of years, and HTML5-powered games running at a constant 60 fps are already a reality.

It wasn’t easy. For Internet Explorer 9, this meant writing an all-new JavaScript engine that can use multiple CPU cores and a fully hardware-accelerated rendering pipeline based on Direct2D. In other words: If you’ve spent good money on your gaming rig, Internet Explorer 9 will make good use of it.

Internet Explorer 9’s integrated JavaScript profiler helps you locate performance bottlenecks.

For simple games, this means that you don’t have to worry about performance. But since HTML5 is platform agnostic, you’re potentially developing for a whole range of devices and browsers, some of which won’t be as fast as you’d like. Even if you’re only targeting high-powered PCs (something we said we wouldn’t do, remember?), performance can still become an issue.

If you want your game to run at 60 fps, you have no more than 16 milliseconds to render any individual frame. In the time it takes for you to blink, you have to render at least 6 complete frames. Now this may seem like a daunting task…and with any non-trivial game, it certainly can be.

Luckily, there are tools that can help you. In Internet Explorer 9 (or 10 for that matter), hit the F12 key to open the developer tools. Select the "Profiler" tab and hit "Start profiling".

Now navigate to where you feel performance should be better, give the profiler about 30 seconds to gather data, then hit "Stop profiling." You will be presented with an overview of how much accumulated execution time is consumed by each of the functions of your game. Most of the time, you’ll find that there are a number of functions that take up the majority of the overall execution time. Optimizing these functions will give you the most bang for your buck and, when you analyze your code, slow subroutines will immediately stick out.

Don’t trust your instincts all too blindly though—code that looks slow might actually execute quite fast with today’s JavaScript engines. The best approach to optimization is to re-profile often and to always measure if the changes you make to your code actually have a positive impact on performance.

Gaming gone social: Warimals is based on HTML5 and allows you to play alongside your Facebook friends.

Best practice #5: Be creative!

To be able to write games that run natively in your browser is pretty awesome, but what’s even cooler is that HTML5 allows you to write games that RUN IN YOUR BROWSER! Not only is HTML5 interesting from a technology point of view, a browser is also a perfect platform for gaming.

Think about it…browsers exist on many different devices, they’re (almost) always online, and they’re a tool people use to connect with each other via email, chat and social networking. As a browser game developer, you can build games that are fun and bring together people from all over the world.

If you’re new to HTML5 game development, it might be tempting to write clones of games you’ve played offline. There is absolutely nothing wrong with this approach. But if you think of your game running inside a "communication application," there’s a good chance you’ll come up with all-new, highly creative game ideas. An interesting example of this is Warimals, one of the first HTML5-based Facebook games. In Warimals, you can play either as dogs or kittens, and you can invite your Facebook friends to play along with you. What’s not to like?

To sum up ...

Thanks to the great work of framework developers and JavaScript pioneers, HTML5 has already become a fairly mature platform for writing games. This is great news, because the Web is the single most ubiquitous runtime for applications of any kind. With the right tools (many of which are conveniently integrated into Internet Explorer 9 and 10 or can be downloaded for free) and the right framework, the HTML5 game development experience can be pleasant and greatly rewarding, especially when creating connected experiences in interesting and innovative ways.

Tools to get you started


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Kai Jager
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170308.1 | Last Updated 15 Mar 2012
Article Copyright 2012 by Kai Jager
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid