The Complete Guide to Building HTML5 Games with Canvas & SVG
by David Rousset
I’m currently spending most of my time explaining to students, hobbyists, professional developers and teachers how to build games using HTML5. I then recently thought: rather than keeping all these details for small audiences, wouldn’t it be smarter to share it with you?
This article is then based on my own experience. I will probably omit some crucial things some of you may know. But it will try to update this blog post along with my own new discovers and of course based on the feedbacks you will kindly provide in the comments or via Twitter.
But why are so many people currently interested in HTML5 Gaming?
Well, simply because today, we can really use HTML5 to target multi-platforms using the same code: for desktop machines of course (with IE9/IE10, Firefox, Chrome, Opera & Safari), for iOS & Android tablets & phones and Windows 8, and its future associated millions of tablets & PC, is also warmly welcoming HTML5 Games! I then frequently see some HTML5 gaming projects ported to each of these platforms with almost no effort.
Note: we will only talk about the <canvas> tag of HTML5 and about SVG in this article.
Canvas & SVG: 2 ways to draw on the screen
The first thing you need to understand before building your first HTML5 game is how to draw nice objects on the screen. There are 2 ways to do that and to better understand their differences, you should start by reading this article from Patrick Dengler (member of the SVG W3C Working Group): Thoughts on when to use Canvas and SVG
On my side, I’ve re-used parts of Patrick’s materials to build a 45min internal session for my Microsoft’s colleagues last year. You can watch it via this video I’ve made (using HTML5 <video> of course!):
00:00 / 00:00
And here are the slides:
At last, you can download the source code I’m demonstrating in this video here: Mix11SVGCanvas.zip
You may have a look also to these 2 great sessions from MIX11:
Once you will have reviewed all this content, you will probably better understand why almost all HTML5 games are using Canvas rather than SVG. Canvas offers a well-known development model for games developers (low level drawing APIs) and is now very well hardware-accelerated by most of the recent browsers. Still SVG, and its vectors-based technology, is naturally better armed to scale across devices without loosing quality. You just need to use the magic ViewBox property of SVG which will handle that for you. Your games assets will then scale from 3 to 80’’ screens in a very easy way!
Sometimes, it is even possible to achieve the exact same game using both technologies. For instance, here is the same simple game first using SVG then Canvas: SVG Racketball & Canvas Racquetball They are both issued from this MSDN documentation: Programming Simple Games Using Canvas or SVG
In this case, analyzing the performance of each technology could help you to decide which one to use for your game. For instance, here is an 2 interesting experiments that will display 1000 small balls on your screen using SVG: 1000 balls in SVG and using Canvas: 1000 balls in Canvas. Test both experiments in your favorite browser. In general, the Canvas performance is better for drawing a lot of objects on the screen in this special case. But this is generally also what we’d like to achieve in our video games. To have a better overview of the performance comparison, here is an interesting diagram to look at:
But nothing prevents you from mixing both technologies. Indeed, we could perfectly imagine using a first layer based on SVG to display the game menus with a second layer in background using a canvas for the game itself. You will then use what we call the browser compositing engine. However, you must pay some real attentions to final performance results because the browsers & devices are far from being equals in this domain. Don’t forget that the main interest of HTML5 is to target all platforms.
Useful libraries & tools
Writing the XML nodes of SVG manually or even playing with the low level APIs of Canvas could be fun for a moment but not very productive. Here is then a useful set of tools & libraries I like that could help you building parts of your HTML5 game.
To generate some SVG, here are some cool tools:
- InkScape: a free & open source desktop software
- SVG Editor: an online software running directly inside your browser
Adobe Illustrator also supports SVG as an export target but it’s a bit more expensive. ;-)
If you’re looking for your game assets (for menus or controls), you should have a look to this free icons library: The Noun Project. So if you’re not lucky enough to work with a designer, it could save you. There is another library with some free SVG content also here: Open Clip Art Library
Note: we can also combine all of these graphics effects with the usage of CSS3 2D & 3D Transforms coupled with transitions or animations in your game. But I’ve decided to stay focused on Canvas & SVG in this article.
Of course, displaying graphics is far from being the only task you need to do in a game. There is also the AI (Artificial Intelligence) you need to code to bring life to your characters. Unfortunately, you will need to code that alone and be creative. But you will be glad to know you don’t need to worry about the physics & collisions part of your game. Simply learn to how to use Box2D JS. Go play with the various samples and you’ll be amazed:
Handling the multi touch events
If you’d like to build a cross-devices game, you will have to support touch. Currently, there are 2 existing specifications around Touch Events. So there is no official standard one yet. If you’d like to know a bit more why, here is an interesting article: Getting Touchy About Patents
You will need to write code working fine inside IE10 & Windows 8 as well as with the implementation coming from the Apple devices. For that, you should definitely have a look to this sample demonstrating a possible pattern to support both kind of touch events: Finger Painting and its associated article: Handling Multi-touch and Mouse Input in All Browsers. But if you’re interesting in checking how far you can now go by handling multi-touch inside IE10, test this cool demo: Browser Surface . You’ll need a recent IE10 version and a multitouch hardware running it.
Boris Smus has started working on his side on a library named Pointer.js. The idea is to consolidate all types of touch (IE10, iOS like, mouse and pen) to simplify your developer life. You can read his article about that here: Generalized input on the cross-device web . Currently, the library is just a draft and doesn’t support yet the MSPointer* of IE10. So feel free to contribute to the project to help him! (I’ve planned to try to help him when I will have some spare time).
Building connected games
If you’d like to build multiplayers games or simply a connected game to a server for any reason, you’ll be naturally interested by using WebSockets. This W3C specification (and the underlying protocol handled by the IETF) is indeed stable enough to start to be used in production.
But if you’d like to support the widest possible number of users, you need to consider a fallback for browsers or devices which weren’t supporting WebSockets yet or were supporting an older deprecated version. Well, we could even dream of solutions automatically falling back to older method of pooling or long pooling for browsers like IE9 and offering Web Sockets to more recent browsers like IE10. And yes, could it be possible also to have a unique code handling that?
Well, stop dreaming, the community made it. There are 2 solutions I know doing that on my side:
Both libraries will help you to handle all the browsers & devices with their variety of support levels.
Some gaming frameworks
To build a 2D HTML5 game, there are several things you need to carry about:
1 – Handling your sprites: splitting them into a sequence, animating them, effects, etc.
2 – Handling your sounds & music (and this is not something easy in HTML5!)
3 – Loading asynchronously your assets from the web server via a dedicated loader/assets manager
4 – Building a collision engine, a high level logic for your game objects, etc.
Well, you can either do that starting from scratch or you can test & review what other brilliant developers have already done on the web. I’ll definitely advice you the second option as the JS gaming frameworks start to be really mature and tested inside games in production.
As there is a ton of JS gaming frameworks on the web (well, there is a ton of anything.JS actually), here are the most well-known frameworks I know to build HTML5 2D games working inside all browsers:
- MelonJS : a free framework that exposes a lot of useful services. His big advantage is that it works fine with the Tiled Map Editor tool.
- CraftyJS that I unfortunately don’t know very well
- ImpactJS : a high quality well-known framework. It’s not free but not too much expensive.
- EaselJS : my favorite one ! Written by an old flash developer. So if you have written some games in Flash, you should feel at home with this framework. It’s part of the CreateJS suite. It’s very complete, well documented and… free.
So, you should now be warn. As EaselJS is the framework I know the most, I won’t be impartial. It’s up to you to test the other one and make your own opinion.
Some beginners’ tutorials
- HTML5 Gaming: animating sprites in Canvas with EaselJS
- HTML5 Gaming: building the core objects & handling collisions with EaselJS
- HTML5 Platformer: the complete port of the XNA game to <canvas> with EaselJS
Several months later, I’ve done 3 others articles enhancing/extending the same game:
- Tutorial: how to create HTML5 applications on Windows Phone thanks to PhoneGap where I’ll show you how to port the same game on Windows Phone thanks to PhoneGap/Cordova. But you will be able to follow the same instructions for your Android or iOS device.
- Modernizing your HTML5 Canvas games Part 1: hardware scaling & CSS3 where we’ll use CSS3 3D Transform, Transitions & Grid Layout to enhance the gaming experience
- Modernizing your HTML5 Canvas games Part 2: Offline API, Drag’n’drop & File API where we will enable playing to the game in offline mode. You will be even able to create your own levels and drag’n’drop them directly into the game.
After following them, you’ll build this game: