Schweitzer Fachinformationen
Wenn es um professionelles Wissen geht, ist Schweitzer Fachinformationen wegweisend. Kunden aus Recht und Beratung sowie Unternehmen, öffentliche Verwaltungen und Bibliotheken erhalten komplette Lösungen zum Beschaffen, Verwalten und Nutzen von digitalen und gedruckten Medien.
Bitte beachten Sie
Am Mittwoch, den 22.10.2025, finden bei unserem externen E-Book Dienstleister zwischen 07.00 und 10.00 Uhr Wartungsarbeiten statt. Daher bitten wir Sie Ihre E-Book Bestellung außerhalb dieses Zeitraums durchzuführen. Möglicherweise kann die Zustellung des Download-Links auch außerhalb der Wartungsarbeiten an diesen Tagen zeitverzögert sein. Wir bitten um Ihr Verständnis. Bei Problemen und Rückfragen kontaktieren Sie gerne unseren Schweitzer Fachinformationen E-Book Support.
Jacob Seidelin (Copenhagen) is a freelance web developer with 10 years of experience working with both backend programming, graphics design and front-end technology. When not working with clients of all sizes he enjoys JavaScript and HTML5, web game development and generally pushing the limit of what is possible in the browser. The results of his adventures in web development can be witnessed at his website at www.nihilogic.dk
Who this book is for 2
What this book is about 2
Part I Getting Started with HTML5 Games 5
CHAPTER 1 Gaming on the Web 7
Tracing the History of HTML5 8
Using HTML5 for Games 8
Canvas 9
Audio 11
WebSockets 12
Web Storage 13
WebGL 14
HTML5 and Flash 14
Creating Backward Compatibility 15
Using feature detection 15
Filling the gaps with polyfills 16
Building a Game 16
Summary 17
CHAPTER 2 Taking the First Steps 19
Understanding the Game 20
Swapping jewels 20
Matching three 20
Level progression 20
Identifying Game Stages 21
Splash screen 21
Main menu 22
Playing the game 22
High score 23
Creating the Application Skeleton 24
Setting up the HTML 25
Adding a bit of style 26
Loading the scripts 27
Creating a DOM helper module 31
Creating the Splash Screen 35
Working with web fonts 36
Styling the splash screen 37
Summary 40
CHAPTER 3 Going Mobile 41
Developing Mobile Web Applications 42
Write once, read many 42
Th e challenges of mobile platforms 43
Handling User Input on Mobile Devices 43
Keyboard input 43
Mouse versus touch 44
Adapting to Small Screen Resolutions 45
Creating scalable layouts 46
Controlling the viewport 48
Disabling user scaling 49
Creating Different Views 50
Creating the main menu 50
Adding screen modules 52
Using CSS media queries 56
Detecting device orientation 58
Adding a landscape style sheet 59
Developing for iOS and Android Devices 62
Placing web applications on the home screen 62
Getting the browser out of the way 71
Debugging Mobile Web Applications 73
Enabling the Safari debugger 74
Debugging on Android 76
Building Native Web Applications 77
PhoneGap 77
Future Mobile Platforms 81
Summary 81
Part II Creating the Basic Game 83
CHAPTER 4 Building the Game 85
Creating the Game Board Module 85
Initializing the game state 87
Filling the initial board 90
Implementing the Rules 93
Validating swaps 93
Detecting chains 95
Refilling the grid 100
Swapping jewels 104
Summary 105
CHAPTER 5 Delegating Tasks to Web Workers 107
Working with Web Workers 107
Limitations in workers 108
What workers can do 109
Using Workers 110
Sending messages 111
Receiving messages 111
Catching errors 112
Shared workers 112
A prime example 114
Using Web Workers in Games 117
Creating the worker module 117
Keeping the same interface 120
Summary 125
CHAPTER 6 Creating Graphics with Canvas 127
Ways to Display Graphics on the Web 128
Bitmap images 128
SVG graphics 128
The canvas element 129
When to choose canvas 129
Drawing with canvas 130
Drawing shapes and paths 131
Using advanced strokes and fill styles 142
Using transformations 147
Adding text, images, and shadows 151
Managing the state stack 156
Drawing the HTML5 logo 157
Compositing 164
Accessing Image Data 167
Retrieving pixel values 167
Updating pixel values 168
Exporting image fi le data 170
Understanding security restrictions 171
Creating pixel-based eff ects 171
Summary 174
CHAPTER 7 Creating the Game Display 175
Tracking Load Progress 176
Adding a progress bar 177
Building the Game Screen 180
Drawing the board with canvas 181
Exiting the game 188
Pausing the game 191
Summary 194
CHAPTER 8 Interacting with the Game 195
Capturing User Input 196
Mouse events on touch devices 196
The virtual keyboard 196
Touch events 198
Input events and canvas 204
Using gamepads and controllers 206
Building the Input Module 211
Handling input events 214
Implementing game actions 220
Binding inputs to game functions 226
Summary 233
CHAPTER 9 Animating Game Graphics 235
Making the Game React 236
Animation timing 236
Animating the cursor 241
Animating game actions 243
Adding Points and Time 253
Creating the UI elements 254
Creating the game timer 259
Pausing the game 261
Awarding points 263
Game over 272
Summary 277
Part III Adding 3D and Sound 279
CHAPTER 10 Creating Audio for Games 281
HTML5 Audio 282
Detecting audio support 282
Understanding the audio format wars 283
Finding sound effects 285
Using the audio Element 286
Controlling playback 289
Using audio on mobile devices 293
Working with Audio Data 294
Using the Web Audio API 295
Building the Audio Module 300
Preparing for audio playback 300
Playing sound effects 301
Stopping sounds 303
Cleaning up 304
Adding Sound Effects to the Game 305
Playing audio from the game screen 305
Summary 306
CHAPTER 11 Creating 3D Graphics with WebGL 309
3D for the Web 310
Where you can use WebGL 310
Getting started with WebGL 310
Debugging WebGL 311
Creating a helper module 312
Using Shaders 313
Variables and data types 313
Using shaders with WebGL 319
Uniform variables 325
Varying variables 326
Rendering 3D Objects 327
Using vertex buffers 328
Using index buffers 329
Using models, views, and projections 331
Rendering 336
Loading Collada models 341
Using Textures and Lighting 343
Adding light 344
Adding per-pixel lighting 348
Creating textures 351
Creating the WebGL display 358
Loading the WebGL files 359
Creating the jewel objects 360
Setting up WebGL 362
Rendering jewels 364
Animating the jewels 371
Using Th ird-Party WebGL Engines 375
Summary 376
Part IV Local Storage and Multiplayer Games 377
CHAPTER 12 Local Storage and Caching 379
Storing Data with Web Storage 379
Using the storage interface 380
Building a storage module 384
Making the Game State Persistent 385
Saving the game data 385
Creating a High Score List 389
Building the high score screen 389
Storing the high score data 392
Displaying the high score data 394
Application Cache 395
The cache manifest 396
Summary 399
CHAPTER 13 Going Online with WebSockets 401
Using WebSockets 401
Connecting to servers 402
Communicating with WebSockets 405
Using Node on the Server 407
Installing Node 408
Creating an HTTP server with Node 410
Creating a WebSocket chat room 412
Summary 420
BONUS CHAPTER: APPENDIX A
Canvas Reference BC1
The Canvas Element BC1
The 2D Context API BC2
State management BC2
Transformations BC3
Shapes and Paths BC4
Path Objects BC9
Fills and Strokes BC11
Shadows BC13
Images BC14
Text BC15
Compositing BC16
Pixel manipulation BC17
BONUS CHAPTER: APPENDIX B
WebGL Reference BC19
WebGL API Reference BC19
Data types BC20
Typed arrays BC21
Context properties BC21
Buffers BC22
Shaders BC23
Program objects BC24
Uniform variables BC25
Vertex attributes BC27
Drawing BC28
Textures BC29
Blending BC33
Stencil buffer BC34
Depth buffer BC35
Render buffers BC35
Frame buffers BC37
Other methods BC39
Parameters BC40
BONUS CHAPTER: APPENDIX C
OpenGL ES Shading Language BC47
GLSL ES Language Reference BC47
Data types BC47
Built-in functions BC49
Built-in variables and constants BC57
Index 421
Chapter 1
In This Chapter
• Finding out what HTML5 is and where it came from
• Seeing HTML5 within the context of games
• Looking at important new features
• Enabling feature detection and dealing with legacy browsers
BEFORE I DIVE into code, I want to establish the context of the technology we use. In this first chapter, I discuss what HTML5 is as well as some of the history that led to the HTML5 specification.
One of the most interesting aspects of HTML5 is how game developers can profit from many of its new features. In this chapter, I introduce you to some of those features and give you a few quick examples of how to use them. I talk about the canvas element and WebGL and the huge improvement they make in creating dynamic graphics. I also cover the audio element and the added multiplayer possibilities created by the WebSocket specification.
Everybody likes new toys, but remember that in the real world, old and outdated browsers keep many users from taking advantage of these cutting-edge features. In this chapter, I discuss a few tools that can help you detect which features you can safely use as well as how you can use these feature tests to load appropriate fallback solutions when necessary.
Finally, I briefly introduce the puzzle game that I use throughout the rest of the book to take you through the creation of a complete HTML5 game.
HTML, the language of the web, has gone through numerous revisions since its invention in the early 1990s. When Extensible Markup Language (XML) was all the rage around the turn of the millennium, a lot of effort went into transforming HTML into an XML-compliant language. However, lack of adoption, browser support, and backward compatibility left the web in a mess with no clear direction and a standards body that some felt was out of touch with the realities of the web.
When the W3C finally abandoned the XHTML project, an independent group had already formed with the goal of making the web more suitable for the type of web applications you see today. Instead of just building upon the last specification, the Web Hypertext Application Technology Working Group (WHATWG) began documenting existing development patterns and non-standard browser features used in the wild. Eventually, the W3C joined forces with the WHATWG. The two groups now work together to bring new and exciting features to the HTML5 specification. Because this new specification more closely reflects how web developers already use the web, making the switch to HTML5 is easy, too. Unlike previous revisions, HTML5 doesn't enforce a strict set of syntax rules. Updating a page can often be as easy as changing the document type declaration.
But what is HTML5? Originally, it referred to the latest revision of the HTML standard. Nowadays, it's harder to define; the term has gone to buzzword hell and is now used to describe many technologies that aren't part of the HTML5 specification. Even the W3C got caught up in the all-inclusiveness of HTML5. For a brief period, they defined it as including, for example, Cascading Style Sheets (CSS) and Scalable Vector Graphics (SVG). This only added to the confusion. Fortunately, the W3C backed away from that stance and went back to the original, stricter definition that refers only to the actual HTML5 specification. In a somewhat bolder move, the WHATWG simply dropped the numeral 5, renaming it simply HTML. This actually brings it much closer to reality, in the sense that specifications such as HTML are always evolving and never completely supported by any browser. In this book, I just use the term HTML for the most part. You can assume that any mention of HTML5 refers to the actual W3C specification called HTML5.
Many features from the HTML5 specification have applications in game development, but one of the first features to gain widespread popularity was the canvas element. The visual nature of this element without a doubt helped it spread quickly when the first interactive animations and graphics effects started appearing. More advanced projects soon followed, giving the new standard a dose of good publicity and promising a future with a more dynamic and visually interesting web.
Hobbyist game developers were also among the first to embrace HTML5, and for good reason. The canvas element provides web game developers with the ability to create dynamic graphics, giving them a welcome alternative to static images and animated GIFs.
Sure, people have created more or less ingenious (and/or crazy) solutions in lieu of better tools for creating dynamic graphics. Entire drawing libraries rely on nothing more than colored div elements—that may be clever, but that approach isn't sufficient for doing anything more than drawing a few simple shapes.
Uniform Resource Identifier (URI) schemes let you assign source files to img elements, for example, using a base64-encoded data string, either directly in the HTML or by setting the src or href property with JavaScript. One of the clever uses of this data URI scheme is to generate images on the fly and thus provide a dynamically animated image, which isn't a great solution for anything but small and simple images.
Wolf 5K, the winner of the 2002 The 5K contest, which challenged developers to create a website in just five kilobytes, used a somewhat similar technique. The game, a small 3D maze game, generated black and white images at runtime and fed them continuously to the image src property, relying on the fact that img elements can also take a JavaScript expression in place of an actual URL.
Graphics drawn on a canvas surface can't be declared with HTML markup; instead, they must be drawn with JavaScript using a simple Application Programming Interface (API). Listing 1-1 shows a basic example of how to draw a few simple shapes. Note that the full API provides much more functionality than the small portion shown in this example.
Listing 1-1 Drawing shapes with the canvas API
<canvas id="mycanvas"></canvas> <script> var canvas = document.getElementById("mycanvas"), ctx = canvas.getContext("2d"); canvas.width = canvas.height = 200; // draw two blue circles ctx.fillStyle = "blue"; ctx.beginPath(); ctx.arc(50, 50, 25, 0, Math.PI * 2, true); ctx.arc(150, 50, 25, 0, Math.PI * 2, true); ctx.fill(); // draw a red triangle ctx.fillStyle = "red"; ctx.beginPath(); ctx.moveTo(100, 75); ctx.lineTo(75, 125); ctx.lineTo(125, 125); ctx.fill(); // draw a green semi-circle ctx.strokeStyle = "green"; ctx.beginPath(); ctx.scale(1, 0.5); ctx.arc(100, 300, 75, Math.PI, 0, true); ctx.closePath(); ctx.stroke(); </script>
The code produces the drawing shown in Figure 1-1.
Figure 1-1: This simple canvas drawing was created with JavaScript.
I revisit the canvas element in Chapter 6 and explore it in detail when I use it to create game graphics and special effects.
The new audio element is just as welcome to a web game developers’ toolbox as the canvas element. Finally, you have native audio capabilities in the browser without resorting to plug-ins. Not too long ago, if a website had audio, some form of Flash was involved. Libraries like the SoundManager 2 project (www.schillmania.com/projects/soundmanager2) provide full JavaScript access to most of the audio features of Flash. But even if such a bridge allows your own code to stay on the JavaScript side, your users still need to install the plug-in. The HTML5 audio element solves this problem, making access to audio available in browsers out of the box using only plain old HTML and JavaScript.
The audio element still has a few unresolved issues, however. The major browser vendors all seem to agree on the importance of the element and have all adopted the specification, but so far they've failed to agree on which audio codecs should be supported. So, while the theory of the audio element is good, reality has left developers with no other option than to provide audio files in multiple formats to appease all the browser vendors.
The audio element can be defined in the mark-up or created dynamically with JavaScript. (The latter option is of more interest to you as an application and game developer.) Listing 1-2 shows a basic music player with multiple source files, native user interface (UI) controls, and a few keyboard hotkeys that use the JavaScript API.
Listing 1-2 A simple music player with HTML5 audio
<audio...
Dateiformat: ePUBKopierschutz: Adobe-DRM (Digital Rights Management)
Systemvoraussetzungen:
Das Dateiformat ePUB ist sehr gut für Romane und Sachbücher geeignet – also für „fließenden” Text ohne komplexes Layout. Bei E-Readern oder Smartphones passt sich der Zeilen- und Seitenumbruch automatisch den kleinen Displays an. Mit Adobe-DRM wird hier ein „harter” Kopierschutz verwendet. Wenn die notwendigen Voraussetzungen nicht vorliegen, können Sie das E-Book leider nicht öffnen. Daher müssen Sie bereits vor dem Download Ihre Lese-Hardware vorbereiten.Bitte beachten Sie: Wir empfehlen Ihnen unbedingt nach Installation der Lese-Software diese mit Ihrer persönlichen Adobe-ID zu autorisieren!
Weitere Informationen finden Sie in unserer E-Book Hilfe.