HTML5 Game Development by Example: Beginner's Guide - Second Edition - Sample Chapter
HTML5 Game Development by Example: Beginner's Guide - Second Edition - Sample Chapter
ee
HTML5 Game Development by Example Beginner's Guide Second Edition is a step-by-step tutorial that will
help you create several games from scratch, with useful examples. Starting with an introduction to HTML5,
the chapters of this book help you gain a better understanding of the various concepts and features of HTML5.
By the end of the book, you'll have the knowledge, skills, and level of understanding you need to efficiently
develop games over the network using HTML5.
HTML5 is a markup language used to structure and present content for the World Wide Web and is a core
technology of the Internet. It is supported across different platforms and is also supported by various browsers.
Its innovative features, such as canvas, audio, and video elements, make it an excellent game building tool.
Beginner's Guide
useful tasks
pl
e
Second Edition
Makzan
$ 44.99 US
29.99 UK
P U B L I S H I N G
Sa
Beginner's Guide
P U B L I S H I N G
Makzan
Preface
HTML5 promises to be the hot new platform for online games. HTML5 games work on
computers, smartphones, tablets, iPhones, and iPads. Be one of the first developers to
build HTML5 games today and be ready for tomorrow!
This book will show you how to use the latest HTML5 and CSS3 web standards to build
card games, drawing games, physics games, and even multiplayer games over the network.
With this book, you will build six example games with clear systematic tutorials.
HTML5, CSS3, and the related JavaScript API are the latest hot topic in the Web. These
standards bring us the new game market of HTML5 games. With the new power from
them, we can design games with HTML5 elements, CSS3 properties, and JavaScript to
play in browsers.
The book is divided into 10 chapters with each one focusing on one topic. While building
the six games in the book, you will learn how to draw game objects, animate them, add
audio, connect players, and build physics game with the Box2D physics engine.
Preface
Chapter 4, Building the Untangle Game with Canvas and the Drawing API, introduces a
new way to draw things and interact with them in a web page with the new canvas element.
This also demonstrates how to handle dragging on touch devices.
Chapter 5, Building a Canvas Game's Masterclass, extends the Untangle game to show how
we can draw gradients and images in the Canvas. It also discusses sprite sheet animations
and multilayer management.
Chapter 6, Adding Sound Eects to Your Games, adds sound eects and background music
to the game by using the Audio element. It discusses the audio format capability among
web browsers and creates a keyboard-driven music game by the end of the chapter.
Chapter 7, Saving the Game's Progress, extends the CSS3 memory-matching game to
demonstrate how we can use the Local Storage API to store and resume game progress
and records the best scores.
Chapter 8, Building a Multiplayer Draw-and-Guess Game with WebSockets, discusses the
WebSockets API that allows browsers to establish persistent connection with the socket
server. This allows multiple players to play the game together in real time. A draw-and-guess
game is created at the end of the chapter.
Chapter 9, Building a Physics Car Game with Box2D and Canvas, teaches you how to integrate
a famous physics engine, Box2D, into our canvas games. It discusses how to create physics
bodies, apply force, connect them together, associate graphics with the physics, and finally
create a platform car game.
Chapter 10, Deploying HTML5 Games, shares the dierent ways in which we can publish
our games. It discusses wrapping the web into a native app for Apple's App Store.
Appendix, Pop Quiz Answers, gives the answers to the pop quiz questions in each of
the chapters.
There are modern web browsers in most desktop and mobile devices. These latest web
techniques bring us the new game marketthe HTML5 games. With the new power
from these techniques, we can design games with HTML5 elements, CSS3 properties,
and JavaScript to play in most browsers and mobile devices.
In this chapter, we will cover the following topics:
Canvas
Canvas is an HTML5 element that provides drawing shapes and bitmap manipulation
functions in low levels. We can imagine the Canvas element as a dynamic image tag.
The traditional <img> tag shows a static image. This image is usually static after it's
loaded. We can change the <img> tag to another image source or apply styles to the
image, but we cannot modify the image's bitmap context itself.
On the other hand, Canvas is like a client-side dynamic <img> tag. We can load images
inside it, draw shapes there, and interact with it using JavaScript.
Canvas plays an important role in HTML5 game development. It is one of our main focus
areas in this book.
Audio
Background music and sound eects are essential elements in game design. HTML5 comes
with native audio support from the audio tag. Thanks to this feature, we do not require
the proprietary Flash Player to play sound eects in our HTML5 games. However, there
have been some restrictions on using Web Audio on the Web. We will discuss the usage
of the audio tag in Chapter 6, Adding Sound Eects to Your Games.
Touch Events
Besides the traditional keyboard and mouse events, there are touch events that we can use
to handle single and multi-touch events. We can design a game that works on mobile devices
with touches. We can also handle gestures by observing the touch patterns.
GeoLocation
GeoLocation lets the web page retrieve the latitude and longitude of the user's computer.
For example, Google's Ingress game makes use of GeoLocation to let players play the game in
their real city. This feature may not have been so useful years ago when everyone was using
the Internet with their desktop. There are not many things for which we need the accurate
location of the road of the user. We can get the rough location by analyzing the IP address.
[2]
Chapter 1
These days, more and more users are going on the Internet with their powerful smartphones.
Webkit and other modern mobile browsers are in everyone's pocket. GeoLocation lets us
design mobile applications and games to play with the inputs of a location.
WebGL
WebGL extends the Canvas element by providing a set of 3D graphics APIs in the web
browser. The APIs follow the standard of OpenGL ES 2.0. WebGL provides a powerful
GPG-accelerated, 3D rendering API for HTML5 games. Some 3D game engines support
the export of WebGL, including the popular Unity engine. We can expect to see more
HTML5 3D games waiting to be released using WebGL.
The techniques used to create games with WebGL are quite dierent than using Canvas.
Creating games in WebGL requires handing the 3D models and using an API similar to
OpenGL. Therefore, we will not discuss WebGL game development in this book.
WebGL has a better performance than 2D Canvas because of the GPU-rendering support.
Some libraries allow a game to use Canvas 2D drawing API, and the tools render the
canvas by drawing on WebGL to gain performance. Pixi.js (http://www.pixijs.com),
EaselJS (http://blog.createjs.com/webgl-support-easeljs/) and WebGL-2D
(https://github.com/corbanbrook/webgl-2d) are several such tools among them.
WebSocket
WebSocket is part of the HTML5 spec to connect the web page to a socket server. It provides
us with a persistent connection between the browser and server. This means that the client
does not need to poll the server for new data within short periods. The server will push
updates to the browsers whenever there is any data to update. One benefit of this feature
is that game players can interact with each other in almost real time. When one player does
something and sends data to the server, we can send the individual player the update to
create one-on-one real-time page play, or we can iterate all the connections in the server to
send an event to every other connected browser to acknowledge what the player just did.
This creates the possibility of building multiplayer HTML5 games.
Local storage
HTML5 provides a persistent data storage solution to web browsers.
Local Storage stores key-value pair data persistently. The data is still there after the browser
terminates. Moreover, the data is not limited to be accessible only to the browsers that
created it. It is available to all browser instances with the same domain. Thanks to Local
Storage, we can easily save a game's status, such as progress and earned achievements,
locally in web browsers.
[3]
Another database on web browser is IndexedDB. It's key-value pair too, but it allows storing
objects and querying data with condition.
Offline applications
Normally, we need an Internet connection to browse web pages. Sometimes, we can browse
cached oine web pages. These cached oine web pages usually expire quickly. With the
next oine application introduced by HTML5, we can declare our cache manifest. This is a
list of files that will be stored for later access when there is no Internet connection.
With the cache manifest, we can store all the game graphics, game control JavaScript files,
CSS stylesheets, and the HTML files locally. We can also pack our HTML5 games as oine
games on the desktop or mobile devices. Players can play the games even in the airplane
mode. The following screenshot from the Pie Guy game (http://mrgan.com/pieguy)
shows an HTML5 game being played on an iPhone without an Internet connection; note
the little airplane symbol indicating the oine status:
Chapter 1
Instead of directly drawing and interacting on Canvas' drawing board, new CSS3 properties
let us animate the DOM in dierent ways. This makes it possible to make more complicated
DOM-based browser games.
CSS3 transition
Traditionally, the style changes immediately when we apply a new style to an element.
CSS3 transition renders in-between styles during the style changes of the target elements
over duration. For example, here, we have a blue box and want to change it to dark blue
when we do a mouseover. We can do this by using the following code snippets:
HTML:
<a href="#" class="box"></a>
CSS:
a.box {
display: block;
width: 100px;
height: 100px;
background: blue;
}
a.box:hover {
background: darkblue;
}
The box changes to dark blue immediately when we do a mouseover. With CSS3 transition
applied, we can tween the styles for a specific duration and easing value:
a.box {
transition: all 0.5s ease-out;
}
In the past, we needed JavaScript to calculate and render the in-between styles; this is much
slower than using CSS3 transition because the browser natively makes the eects happen.
[5]
Since some CSS3 specifications are still in the draft stage and not yet fixed,
implementation from dierent browser vendors may have some minor
dierences to the W3C spec. Therefore, browser vendors tend to implement
their CSS3 properties with a vendor prefix to prevent conflict.
Safari uses the -webkit- prefix. Opera uses the -o- prefix. Firefox uses the
-moz- prefix and IE uses the -ms- prefix. Chrome used to use -webkit-,
but now it doesn't use any prefix after switching its engine to Blink. It is a little
complex now to declare a CSS3 property, such as flex, with several lines of the
same rule for several browsers. We can expect the prefix to be dropped after
the property spec is fixed.
In order to make the code cleaner in this book, I will use non-vendor prefix
for all the properties in this book. I recommend you to use JavaScript-based
libraries to automatically add the required vendor prefix for dierent web
browsers. The prefix-free library (http://leaverou.github.io/
prefixfree/) is one of them.
Alternatively, if you are using preprocessors, the compilation process may also
add the necessary vendor prefix for you.
CSS3 transform
CSS3 transform lets us scale the elements, rotate them, and translate their position. CSS3
transform is divided into 2D and 3D. By combining the transform origin and 3D rotation and
translation, we can animate 2D graphics in a 3D space.
CSS3 animation
CSS3 transition is one type of animation. It declares the tweening animation between two
styles of the elements.
CSS3 animation is one step further in animation. We can define key frames of an animation.
Each key frame contains a set of properties that should change at any particular moment.
It is like a set of CSS3 transitions that are applied in sequence to the target element.
The AT-AT Walker (http://anthonycalzadilla.com/css3-ATAT/index-bones.html)
shows a nice demo on creating a skeleton bone animation with CSS3 animation key frames,
transform, and transition. This is shown in the following diagram:
[6]
Chapter 1
[7]
[8]
Chapter 1
[9]
Asteroid-styled bookmarklet
Erik, a web designer from Sweden, created an interesting bookmarklet. This is an asteroidstyled game for any web page. Yes, any web page! It shows an abnormal way to interact with
any web page. It creates a plane on the website you are reading from. You can then fly the
plane using arrow keys and fire bullets using the space bar. The fun part is that the bullets
will destroy the HTML elements on the page. Your goal is to destroy all the things on the web
page that you choose. This bookmarklet is another example of breaking the boundary of usual
browser games. It tells us that we can think outside the box while designing HTML5 games.
The following screenshot shows the plane destroying the contents on the web page:
X-Type
The creator of a Canvas-based game engine named Impact, created this X-Type (http://
phoboslab.org/xtype/) shooting game for dierent platforms, including web browsers,
iOS, and Wii U. The following screenshot shows the game running smoothly in iPhone.
[ 10 ]
Chapter 1
Cursors.io
Cursors.io (http://cursors.io) demonstrates a nicely designed real-time multiplayer
game. Every user controls an anonymous mouse cursor and takes a journey through the
levels of the game by moving the cursor to the green exit. The fun part of the game is that
players must help the others to advance to the level. There are toggles that some cursors
click on them to unlock the doors. The anonymous players must take up the role to help
the others. Someone will take your role so that you can advance to the next level. The more
players that help you, the higher your chance is to succeed in the game. In case only a few
players are playing and you can't experience the game, I have recorded my playing screen
in 12 x speed (at http://vimeo.com/109414542) to let you have a glimpse of how this
multiplayer game works. This has been captured in the following screenshot:
[ 11 ]
[ 12 ]
Chapter 1
Summary
In this chapter, we've learned a lot about the basic information of HTML5 games.
Specifically, we covered new features of HTML5 and CSS3. We gave you a glimpse of what
techniques we will use to create our games in later chaptersCanvas, audio, CSS animation,
and more new features were introduced. We will have many new features to play with. We
discussed why we want to create HTML5 gameswe want to meet the web standard, meet
mobile devices, and break the boundary of a game. We took a look at several existing HTML5
games that were created with dierent techniques, which we will also use. You can test
these games before we create our own. We also previewed the games that we are going
to build in the book. At last, we prepared our development environments.
Now that we've some background information on HTML5 games, we're ready to create our
first DOM-based, JavaScript-driven game in the next chapter.
[ 13 ]
www.PacktPub.com
Stay Connected: