Learn HTML5 by Creating Fun Games


Learn HTML5 by Creating Fun Games Learn one of the most popular markup languages by creating simple yet fun games Rodrigo Silveira BIRMINGHAM - MUMBAI Learn HTML5 by Creating Fun Games Copyright © 2013 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: June 2013 Production Reference: 1190613 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84969-602-9 www.packtpub.com Cover Image by Duraid Fatouhi (duraidfatouhi@yahoo.com) Credits Author Rodrigo Silveira Reviewer Thomas Mak Acquisition Editor Andrew Duckworth Commissioning Editor Shreerang Deshpande Lead Technical Editor Madhuja Chaudhari Technical Editors Veena Pagare Priya Singh Sampreshita Maheshwari Project Coordinator Apeksha Chitnis Proofreaders Aaron Nash Bernadette Watkins Indexer Hemangini Bari Graphics Ronak Dhruv Valentina Dsilva Production Coordinator Nilesh R. Mohite Cover Work Nilesh R. Mohite About the Author Rodrigo Silveira is a web engineer at Deseret Digital Media. His responsibilities include back-end system development, tools, and maintenance, front-end application development and design, and more recently, he's been involved in mobile development of various products on the Android platform. He received his Bachelor's of Science in Computer Science from Brigham Young University, Idaho, as well as an Associate's Degree in Business Management from LDS Business College in Salt Lake City, Utah. His fascination for web development began in his early teenage years, and his skills grew as he discovered the power of a library subscription, a curious and willing mind, and supportive parents and friends. Today Rodrigo balances his time between the three great passions of his life—his family, software development, and video games (with the last two usually being mingled together). About the Reviewer Thomas Mak, also known as Makzan, is a developer with a specialty in web development and game design. He has over ten years of experience building digital products, including real-time multiplayer interaction games and iOS applications. He is currently a founder of game development learning company, 42games (http://42games.net), where he makes game development tutorials and online learning resources. He has written two books with Packt publishing and one screencast series for building Flash Virtual World and making games with HTML5 and related web standards. I would like to thank my family and my wife, Candy Wong, for supporting all my writings. www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support files and downloads related to your book. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM http://PacktLib.PacktPub.com Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books. Why Subscribe? • Fully searchable across every book published by Packt • Copy and paste, print and bookmark content • On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. Table of Contents Preface 1 Chapter 1: An Overview of HTML5 7 What is HTML? 7 A brief history of HTML 8 The evolution of the World Wide Web 8 What is HTML5? 9 HTML5 – the next step in the evolution 9 HTML5 is not a single feature 10 More semantic document structure 10 A warning about performance 15 Native features of the browser 16 Automatic form validation 18 New input types 19 Telephone-friendly hyperlinks 19 CSS-based DOM selectors 19 Text-to-speech 20 CSS3 20 Separation of concerns 20 Reusability of visual design 21 Ease of maintenance 22 Scalability 22 The evolution of CSS 22 Experimental features and vendor prefixes 23 CSS preprocessors 24 CSS3 modules 25 Style attributes 26 Selectors 26 Colors 27 Media queries 28 Table of Contents [ ii ] JavaScript APIs 31 New JavaScript APIs 31 The Web as a platform 32 The Open Web 33 HTML5 – a game changer 34 Learning HTML5 through game development 35 Summary 36 Chapter 2: HTML5 Typography 39 The game 39 Game elements 42 The options widget 43 The game title 43 Boat 44 Sky 44 Waves 44 Tracks 44 Players 44 The main container 45 Words to write 45 Words written 45 The message container 45 The message title 45 The new champion form 46 Leaderboard 46 Game controls 47 HTML 48 The web form 48 Data attributes 51 CSS 51 Web fonts 51 Transitions 52 Animations 53 The text shadows 56 The box shadows 57 The border radius 58 JavaScript 59 Query selectors 60 API usage 60 Web forms 60 New input types 60 Form validation 75 Used in the game 77 Data attributes 78 Table of Contents [ iii ] Used in the game 80 Query selectors 82 Used in the game 85 Web fonts 85 Transitions 86 Animations 89 The text shadow 91 The box shadow 92 The border radius 93 The code 94 The HTML structure 94 JavaScript and logic 95 Summary 100 Chapter 3: Understanding the Gravity of HTML5 101 Browser compatibility 101 Supporting different browsers 102 HTML5 libraries and frameworks 103 jQuery 103 Google Web Toolkit 105 Supporting browsers with limited HTML5 features 106 Gracefully degrade 106 Polyfills 109 Modernizr 109 The game 110 Code structure 111 API usage 113 Web audio 113 Scalable Vector Graphics (SVG) 115 Drag-and-drop 117 Web audio 119 How to use it 120 SVG 122 How to use it 126 Drag-and-drop 136 How to use it 137 Summary 139 Chapter 4: Using HTML5 to Catch a Snake 141 The game 142 API usage 143 How to use it 143 Typed arrays 147 How to use it 149 Table of Contents [ iv ] ArrayBuffer and ArrayBufferView 150 Typed array view types 153 Canvas 154 How to use it 155 clearRect 157 Fill and stroke 158 Lines 159 Shapes 161 Text 162 Transformations 162 Drawing images 163 Manipulating pixels 166 Web workers 169 How to use it 169 Offline application cache 173 How to use it 173 The code 176 Summary 182 Chapter 5: Improving the Snake Game 183 The game 184 API usage 185 Web messaging 185 How to use it 185 Web storage 192 Local storage 194 Session storage 196 IndexedDB 197 IDBFactory 199 IDBOpenDBRequest 200 IDBTransaction 202 readwrite 203 readonly 203 versionchange 203 Getting elements 204 Deleting elements 209 The code 211 Saving the high score 212 Taking screenshots of the game 213 Summary 216 Chapter 6: Adding Features to Your Game 219 Advanced HTML5 APIs 220 WebGL 221 Hello, World! 221 Table of Contents [ v ] Web sockets 231 The connection 233 The server-side code 234 The client-side code 234 Video 235 Attributes 238 Events 238 Geolocation 243 A Google Maps example 247 Upcoming CSS features 249 Programming in the bleeding edge 249 CSS shaders 251 Using custom filters 253 CSS columns 259 The column rule 261 Column breaks 262 CSS regions and exclusions 264 Exclusions 268 Defining shapes 274 Summary 274 Chapter 7: HTML5 and Mobile Game Development 275 Desktop versus mobile 276 Major implementation considerations 277 Screen size and orientation 277 Computing power 278 Battery life 279 Browser differences 279 Best practices 280 Degrade gracefully and enhance progressively 280 Finger-friendly design 283 Save battery life 284 Plan for offline 285 Offering a desktop version 285 Understanding media queries 285 width 288 height 290 device-width 291 device-height 292 orientation 292 aspect-ratio 293 device-aspect-ratio 295 color 298 color-index 299 monochrome 299 Table of Contents [ vi ] resolution 300 scan 301 grid 301 Understanding touch events 302 touchstart 303 touches 303 changedTouches 303 targetTouches 303 touchend 304 touchmove 304 The touch object 305 identifier 305 screenX 307 screenY 307 clientX 307 clientY 308 pageX 308 pageY 308 radiusX 309 radiusY 310 rotationAngle 313 force 313 target 314 The game 314 Code structure 316 /css 316 /img 318 /js 319 /components 319 /entities 328 /widgets 331 Canvas.js 332 EnemyManager.js 335 GameLoop.js 338 PhysicsManager.js 339 Vec2.js 340 main.js 340 index.html 343 Mobile optimizations 343 Combine resources 344 Track touches by IDs 344 Use CSS animations with caution 345 Use separate canvases for each game layer 346 Use image atlases 347 Summary 348 Index 349 Preface If you would like to write a software that can reach billions of people world- wide, then this book will help you get started on that journey. Today, most of the devices people use every day (computers, laptops, tablet computers, smart phones, and so on) are capable of running HTML5 code. What's more, as modern web browsers continue to get more and more powerful, your HTML5-based games and applications can run at or very near native application performance levels. This book will help you learn all about HTML5, including the semantic markup elements, CSS3 styling, and the latest supporting JavaScript APIs. With this knowledge and skill, we'll be able to create fun games that can be played by anyone using a device connected to the Internet. What this book covers Chapter 1, An Overview of HTML5, explains what HTML5 is, and how it fits into the Open Web platform paradigm. It also introduces the three pillars of HTML5, namely the new HTML elements, CSS3, and new JavaScript APIs. Chapter 2, HTML5 Typography, introduces the first game in the book, namely, a DOM-based typography game. The main HTML5 features described in the chapter include web forms, metadata, web fonts, transitions, animation, text shadow, box shadow, window.JSON, and querySelector. Chapter 3, Understanding the Gravity of HTML5, builds a basic jelly-wobbling gravity game. This chapter includes a discussion of cross-browser support, polyfills, and how to get around different API implementations among different browsers. The main HTML5 features described in the chapter include web audio, SVG graphics, and drag-and-drop. Preface [ 2 ] Chapter 4, Using HTML5 to Catch a Snake, creates a traditional snake game using the new HTML5 canvas element, with its accompanying 2D rendering context. Other HTML5 features described in the chapter include web workers, offline storage, and RequestAnimationFrame. Chapter 5, Improving the Snake Game, builds on the same game created in the previous chapter, adding features such as window messaging, web storage, local storage, session storage, and IndexedDB. Chapter 6, Adding Features to Your Game, focuses the discussion on advanced HTML5 concepts, as well as the latest features. Although no game is built in this chapter, the JavaScript and CSS APIs described represent the current state of the art in HTML5 and web development. The major features described in the chapter include WebGL, web sockets, video, geolocation, CSS shaders, CSS columns, and CSS regions and exclusions. Chapter 7, HTML5 and Mobile Game Development, concludes the book by building a 2D space shooter game completely optimized for mobile game play. The focus of the chapter is mobile-specific considerations in web development, including a discussion about the differences between desktop and mobile platforms. The major HTML5 features described in the chapter include media queries and touch events. Setting up the Environment, walks through the setup of a local web development environment, including installing an open source Apache server. In addition to setting up the development environment, it demonstrates how to build a web portal using the new HTML5 elements, from which we can access the games developed throughout the book. This chapter is available online at: http://www.packtpub. com/sites/default/files/downloads/Setting_up_the_Environment.pdf. What you need for this book You need the latest version of a modern web browser, which, at the time of writing' includes Google Chrome, Mozilla Firefox, Safari, Opera, and Internet Explorer (at least Version 10). You also need a basic text editor of your choice, although any code editing software you may be familiar with will also suffice. Prior knowledge of, or experience with HTML, CSS, and JavaScript is helpful, but not required. Who this book is for This book is primarily written for developers with prior experience with game development, who are now making the transition to HTML5. The focus of the book is not the complexities and theories of game development, but rather, it focuses on helping the reader learn HTML5, and how the Open Web platform can be a means to reaching billions of users world-wide. Preface [ 3 ] Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text are shown as follows: "We can include other contexts through the use of the include directive." A block of code is set as follows: [

Lorem Ipsum...

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: tag to represent every single part of the document when describing a structure like the one represented by the following illustration: Figure 1 The previous figure shows a very typical structure of most websites built in the last generation of web design. Such a design could be represented by the following structure:

Lorem Ipsum...

An Overview of HTML5 [ 12 ] While using the
tag for any purpose under the heavens was one way to get the job done, you can see how this can quickly get out of hand, and turn the document into something hard to understand without great inspection. Looking at this type of code becomes especially troublesome when you see a long series of closing
tags—how can you know what each closing tag is actually closing, since all the tags have the same name? Worse yet, how can you know if you have just the right number of closing tags? Another major problem with designing HTML structures after the
paradigm was that each tag was completely meaningless from a semantic point of view. In order to make each
tag slightly more meaningful and self-describing, extra attributes were added, normally in the form an an ID or a class. Again, this solution only added to the problem, since larger, more complex documents required more and more of these attributes, which one had to keep track of, thus increasing the complexity of what should be a simple solution. Thankfully, in HTML5 this problem is solved in a very elegant manner. Seeing that a lot of documents used the
tags for the same purpose, namely to define common sections such as the header, footer, navigation, and main content, new tags were added to represent such common sections. With these new tags, you are now able to visually scan a design structure, and very quickly understand the way information is to be laid out. Furthermore, the need to create endless ID attributes in order to distinguish each
tag is completely gone. Using some of the new tags provided by HTML5, the same design concept from figure 1 can be represented as follows:

Lorem Ipsum...

Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub. com/support and register to have the files e-mailed directly to you. Chapter 1 [ 13 ] You can see how much more descriptive the code becomes. Keep in mind also, that the benefits of this more meaningful structure extend beyond better readability for humans. With the new semantic tags in HTML5, search engines (such as Google, Microsoft's Bing, and Yahoo!) are able to better understand the content of web pages, and can therefore better index your website based on its subject matter, thus making the Web a bit better. Also, by defining your HTML files with more specific tags, screen reader software is able to better understand the contents of web pages, thus allowing users who depend on such software to better use and enjoy the Internet. Since the Internet seems to have made our world completely flat, you should never make the assumption that only your friends and neighbors will be accessing the content you publish online. Not only will your visitors come to your site from other countries and devices (such as smartphones, tablets, and even television sets), but many of the people surfing the Internet (thus, coming to your site to consume the material you make available to them) also have special needs such as visual or audio aid devices or software. For this reason, when you lay down any HTML code, keep that in mind, and consider how a screen reader program might interpret your content, and how easy it will be for that user to use and consume your work. The following tags were added to HTML5 to accomplish this new, more streamlined semantic order. Keep in mind that each tag has several attributes, which we'll discuss in detail when we show sample usage in the next chapter. Also, because of the new data attributes, elements can be extended arbitrarily. The following table has been taken from HTML5 W3C Candidate Recommendation 17 December 2012, which can be found at http://www.w3.org/TR/2012/CR- html5-20121217/. Tag name Description
This tag represents contact information related to its associated article element, or related to the entire document when associated with a body element.
This tag represents a standalone piece of content, such as an article or blog post. Article elements may be nested, in which case a child article node would be associated with its parent, yet it would still be independent of all other pieces of content in the document.