www.it-ebooks.info HTML5 Games Development by Example Beginner's Guide Create six fun games using the latest HTML5, Canvas, CSS, and JavaScript techniques Makzan BIRMINGHAM - MUMBAI www.it-ebooks.info HTML5 Games Development by Example Beginner's Guide Copyright © 2011 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmied in any form or by any means, without the prior wrien permission of the publisher, except in the case of brief quotaons embedded in crical arcles or reviews. Every eort has been made in the preparaon of this book to ensure the accuracy of the informaon presented. However, the informaon 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 informaon about all of the companies and products menoned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this informaon. First published: August 2011 Producon Reference: 1180811 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-849691-26-0 www.packtpub.com Cover Image by Girish Suryawanshi (girish.suryawanshi@gmail.com) www.it-ebooks.info Credits Author Makzan Reviewers Maeo Ferre Henk Jurriens William Malone Acquision Editor David Barnes Development Editor Neha Mallik Technical Editors Pallavi Kachare Azharuddin Sheikh Copy Editor Neha Shey Project Coordinator Zainab Bagasrawala Proofreader Joanna McMahon Indexer Rekha Nair Graphics Geetanjali Sawant Producon Coordinators Melwyn D'sa Adline Swetha Jesuthas Cover Work Melwyn D'sa www.it-ebooks.info About the Author Makzan is the founder of 42games Limited. He has been designing games since he was a child. He likes to see how the well-designed interacons in his games can trigger the emoons and inuence the player. He believes that games should let a player share joyful mes with friends. Therefore, his favorite game type is mulplayer casual games. Makzan also wrote a book named Flash Mulplayer Virtual World. It is about developing a virtual world to play with friends in real me with Adobe Flash and socket server. I would like to thank the enre team from Packt Publishing. The book would not have been possible without the help from all the editors and proofreaders. I thank all the reviewers for providing useful comments from which I have learned a lot. I thank my family for giving me support during the book wring process. www.it-ebooks.info About the Reviewers Maeo Ferre is a soware engineer, an amateur comic-book arst, and an occasional graphic designer, who was drawn into soware development since he played his rst video game. He fell in love with JavaScript at the end of the 20th century, and he sll loves it with the same passion. Currently he is working for Mozilla, aer more than two years in TomTom as a Senior Soware Engineer and Tech Leader. I wish to thank my love, Elisa, for her paence and understanding. I also want to thank my parents, for their connuous support throughout my whole life. Henk Jurriens is a soware developer and developer evangelist, experienced with Java, Groovy and Grails, and HTML5. Henk is passionate about new technologies and loves to talk about it, and so gives dierent presentaons about HTML5, Linked Data, and Groovy and Grails. In addion, Henk founded an HTML5 User Group to promote and share knowledge about HTML5. During the year, dierent meetups are organized. Together with the Google Technology User Group, he organized for example, a HTML5 Hackathon. Last year, Henk also helped with a HTML5 Game Jam and there he saw the potenal of HTML5 Games and this was the reason for him to review this book. With the help of this book, great HTML5 games can be built! William Malone is a soware developer specializing in dialects of ECMAScript (AconScript and JavaScript). He has wrien many arcles about Flash and HTML5 which are available at http://www.williammalone.com. www.it-ebooks.info www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com for support les and downloads related to your book. Did you know that Packt oers eBook versions of every book published, with PDF and ePub les available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entled 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 collecon of free technical arcles, sign up for a range of free newsleers and receive exclusive discounts and oers on Packt books and eBooks. hp://PacktLib.PacktPub.com Do you need instant soluons to your IT quesons? PacktLib is Packt's online digital book library. Here, y ou can access, read and search across Packt's enre 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 enrely free books. Simply use your login credenals for immediate access. www.it-ebooks.info Table of Contents Preface 1 Chapter 1: Introducing HTML5 Games 7 Discovering new features in HTML5 8 Canvas 8 Audio 8 GeoLocaon 8 WebGL 9 WebSocket 10 Local Storage 10 Oine applicaon 11 Discovering new features in CSS3 11 CSS3 transion 12 CSS3 transform 13 CSS3 animaon 14 Learning more detail of new HTML5 and CSS3 features 15 The benet of creang HTML5 games 15 No third-party plugin required 16 Supporng iOS devices without plugin 16 Breaking the boundary of usual browser games 16 Building HTML5 games 18 What others are playing with HTML5 18 Matching game 18 Sinuous 19 Asteroid-styled bookmarklet 19 Quake 2 20 RumpeTroll 21 Scrabb.ly 21 Aves Engine 22 www.it-ebooks.info Table of Contents [ ii ] Browsing more HTML5 games 22 What we are going to create in this book 23 Summary 24 Chapter 2: Geng Started with DOM-based Game Development 25 Preparing the development environment 26 Preparing the HTML documents for a DOM-based game 26 Time for acon – Installing the jQuery library 27 New HTML5 doctype 28 Header and footer 29 Best pracce to place the JavaScript code 29 Running our code aer the page is ready 29 Seng up the Ping Pong game elements 30 Time for acon – Placing Ping Pong game elements in DOM 30 Introducing jQuery 32 Understanding basic jQuery selectors 33 Understanding the jQuery CSS funcon 34 Benets of using jQuery 35 Manipulang game elements in DOM with jQuery 35 Time for acon – Changing posion of elements with jQuery 35 Understanding the behavior of absolute posion 36 Geng a keyboard input from players 37 Time for acon – Moving DOM objects by a keyboard input 38 Understanding a key code 39 Making constants more readable 40 Converng strings to numbers with parseInt funcon 40 Execung JavaScript expressions directly in the Console panel 42 Checking the console window 42 Supporng mulple keyboard input from players 43 Time for acon – Listening to keyboard input with another approach 43 Declaring global variables in a beer way 45 Creang a JavaScript mer with setInterval funcon 46 Understanding Game Loop 46 Moving a DOM object with JavaScript Interval 47 Time for acon – Moving the ball with JavaScript Interval 47 Beginning collision detecon 49 Time for acon – Hing the ball with the paddles 50 Showing text dynamically in HTML 53 Time for acon – Showing the score of both players 53 Summary 56 www.it-ebooks.info Table of Contents [ iii ] Chapter 3: Building a Memory Matching Game in CSS3 57 Moving game objects with CSS3 transion 57 Time for acon – Moving a playing card around 58 2D transforms funcons 61 3D transforms funcons 61 Tweening the styles by using CSS3 transion 62 Creang a card-ipping eect 64 Time for acon – Flipping a card with CSS3 64 Toggling class with jQuery toggleClass funcon 66 Controlling the visibility of overlapped elements by z-index 67 Introducing CSS perspecve property 68 Introducing backface-visibility 69 Creang a card matching memory game 70 Downloading the sprites sheet of playing cards 70 Seng up the game environment 71 Time for acon – Preparing the card matching game 71 Cloning DOM elements with jQuery 77 Selecng the rst child of an element in jQuery by using child lters 77 Vercally aligning a DOM element 77 Using CSS sprite with a background posion 78 Adding game logic to the matching game 79 Time for acon – Adding game logic to the matching game 80 Execung code aer CSS transion ended 83 Delaying code execuon on ipping cards 83 Randomizing an array in JavaScript 83 Storing internal custom data with an HTML5 custom data aribute 84 Accessing custom data aribute with jQuery 85 Making other playing card games 87 Embedding web fonts into our game 87 Time for acon – Embedding a font from Google Font Directory 88 Choosing dierent font delivery services 90 Summary 91 Chapter 4: Building the Untangle Game with Canvas and Drawing API 93 Introducing the HTML5 Canvas Element 94 Drawing a circle in canvas 95 Time for acon – Drawing color circles on canvas 95 Pung fallback content when the web browser does not support canvas 97 Drawing circles and shapes with canvas arc funcon 98 Converng degree to radians 98 Time for acon – Drawing dierent arcs with arc funcon 99 Execung the path drawing in canvas 102 www.it-ebooks.info [...]... www.it-ebooks.info Preface HTML5 promises to be the hot new platform for online games HTML5 games work on computers, smartphones, and tablets, including 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... CSS3 spec status, compatible list, and basic CSS3 codes The benefit of creating HTML5 games We explored several key new features from HTML5 and CSS3 With these features, we can create HTML5 games on browsers But why do we need to do that? What is the benefit of creating HTML5 games? [ 15 ] www.it-ebooks.info Introducing HTML5 Games No third-party plugin required With the native support of all those features... elements by applying different CSS styles These three receipts bring us the new game market, HTML5 Games With the new power from them, we can design games with HTML5 elements, CSS3 properties, and JavaScript to play in the browsers In this chapter, we shall: Discover new features in HTML5 Discuss what makes us so excited around HTML5 and CSS3 Take a look at what others are playing with HTML5 on... designing Preview what games we are going to build in later chapters So let's get started www.it-ebooks.info Introducing HTML5 Games Discovering new features in HTML5 There are many new things introduced in HTML5 and CSS3 Before getting our hands dirty in creating the games, let's take an overview of the new features and see how we can use them to create games Canvas Canvas is an HTML5 element that provides... six example games with clear systematic tutorials HTML5, CSS3, and the related JavaScript API are the latest hot topics in web These standards bring us the new game market, HTML5 Games With the new power from them, we can design games with HTML5 elements, CSS3 properties, and JavaScript to play in browsers This book is divided into nine chapters with each one focusing on one topic We will create six games. .. allow Flash Player running on their Mobile Safaris, HTML5 and related web standard is what they get in their browsers We can reach this user base by creating HTML5 games that optimize for mobiles Breaking the boundary of usual browser games In traditional game designing, we build games within a boundary box We play video games on a television We play Flash games in web browsers with a rectangle boundary... WebSocket to create a real time multiplayers game Most modern browsers are already supporting these features It is now time to build HTML5 games What others are playing with HTML5 It is a good chance to study how different HTML5 games perform by watching other HTML5 games made with different techniques Matching game The Match game (http://10k.aneventapart.com/Uploads/300/) demonstrates a beautiful... Box2D physics engine What this book covers Chapter 1, Introducing HTML5 Games, introduces the new features from HTML5, CSS3, and related JavaScript API It also demonstrates what games we can make with these features and its benefits Chapter 2, Getting Started with DOM-based Game Development, kick-starts the game development journey by creating a traditional Ping Pong game in DOM and jQuery Chapter... and interact with it by JavaScript Canvas plays an important role in HTML5 game development It is one of our main focuses in this book Audio Background music and sound effects are often an essential element in game design HTML5 comes with native audio support by the audio tag Thanks to this feature, we do not require the proprietary Flash Player to play sound effects in our HTML5 games We will discuss... key frames, transform, and transition: Learning more detail of new HTML5 and CSS3 features HTML5Rocks (http://html5rocks.com) from Google provides a solid quick start guide on new HTML5 elements and CSS3 properties Apple also showcases how appealing it can be by using HTML5 in the WebKit-based browser in their homepage (http://apple.com /html5) CSS3 Info (http://www.css3.info) is a blog with the latest . www.it-ebooks.info HTML5 Games Development by Example Beginner's Guide Create six fun games using the latest HTML5, Canvas, CSS, and JavaScript techniques Makzan BIRMINGHAM - MUMBAI www.it-ebooks.info HTML5. 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 mulplayer games. 237 www.it-ebooks.info www.it-ebooks.info Preface HTML5 promises to be the hot new plaorm for online games. HTML5 games work on computers, smartphones, and tablets, including iPhones and iPads. Be one of the rst developers to build HTML5