Main
The Essential Guide to HTML5: Using Games to Learn HTML5 and JavaScript
The Essential Guide to HTML5: Using Games to Learn HTML5 and JavaScript
Jeanine Meyer
0 /
0
How much do you like this book?
What’s the quality of the file?
Download the book for quality assessment
What’s the quality of the downloaded files?
Gain a deep, practical knowledge of HTML and JavaScript that will provide an introduction to programming and enable you to build interactive websites. This completely updated second edition explains HTML, JavaScript and CSS in the context of working examples and contains full-color screen shots of the programs in action.
You'll begin at an introductory level, learning the essentials of HTML5 and JavaScript and programming techniques. Each chapter features either a familiar game such as Hangman, Rock-Paper-Scissors, Craps, Memory, and Blackjack, or a simple type of game, such as a quiz, a maze, or animated simulations. You’ll develop solid programming skills that will help when learning other programming languages. Each chapter contains tables revealing the structure of the program with comments for each line of code.
These examples demonstrate the features introduced with HTML5. You’ll see how to use canvas elements for line drawing. You can include your own audio and video clips, directly controlled by your JavaScript code. For example, the reward for correct completion of a quiz can be the playing of an audio clip and a video clip. You’ll also learn how to use localStorage to store high scores or game preferences on a user's computer for retrieval next time they play. The Essential Guide to HTML5 explores all of this and more.
What You'll Learn
• Understand HTML 5 concepts with the help of easy-to-grasp, appealing examples
• Use HTML5 to explore new avenues for application and game development on the web
• Review important new elements of HTML 5
• Build, test, and upload simple games to a web site.
Who This Book Is For
Both absolute beginners and users with some knowledge of HTML who want to learn the new HTML5 features
You'll begin at an introductory level, learning the essentials of HTML5 and JavaScript and programming techniques. Each chapter features either a familiar game such as Hangman, Rock-Paper-Scissors, Craps, Memory, and Blackjack, or a simple type of game, such as a quiz, a maze, or animated simulations. You’ll develop solid programming skills that will help when learning other programming languages. Each chapter contains tables revealing the structure of the program with comments for each line of code.
These examples demonstrate the features introduced with HTML5. You’ll see how to use canvas elements for line drawing. You can include your own audio and video clips, directly controlled by your JavaScript code. For example, the reward for correct completion of a quiz can be the playing of an audio clip and a video clip. You’ll also learn how to use localStorage to store high scores or game preferences on a user's computer for retrieval next time they play. The Essential Guide to HTML5 explores all of this and more.
What You'll Learn
• Understand HTML 5 concepts with the help of easy-to-grasp, appealing examples
• Use HTML5 to explore new avenues for application and game development on the web
• Review important new elements of HTML 5
• Build, test, and upload simple games to a web site.
Who This Book Is For
Both absolute beginners and users with some knowledge of HTML who want to learn the new HTML5 features
Categories:
Year:
2018
Edition:
1
Publisher:
Apress
Language:
english
Pages:
417 / 429
ISBN 10:
1484241541
ISBN 13:
9781484241547
File:
PDF, 8.05 MB
Your tags:
The file will be sent to your email address. It may take up to 1-5 minutes before you receive it.
The file will be sent to your Kindle account. It may takes up to 1-5 minutes before you received it.
Please note: you need to verify every book you want to send to your Kindle. Check your mailbox for the verification email from Amazon Kindle.
Please note: you need to verify every book you want to send to your Kindle. Check your mailbox for the verification email from Amazon Kindle.
Conversion to is in progress
Conversion to is failed
You may be interested in Powered by Rec2Me
Most frequently terms
var577
canvas335
html328
player293
variable268
array233
javascript209
html5182
tag169
init141
input138
script135
slingshot131
deck122
width120
audio119
invoked118
mouse110
dice109
scissors103
programming101
header97
css96
closes94
video90
files90
browser85
loop85
vertical83
coding83
maze78
font76
img74
mazes72
quiz72
arrays69
drawall67
clause66
dotx63
rgb63
hangman61
cannon60
doty59
src59
moveball58
ctx55
browsers53
onload51
Related Booklists
0 comments
You can write a book review and share your experiences. Other readers will always be interested in your opinion of the books you've read. Whether you've loved the book or not, if you give your honest and detailed thoughts then people will find new books that are right for them.
1
|
2
|
The Essential Guide to HTML5 Using Games to Learn HTML5 and JavaScript — Second Edition — Jeanine Meyer The Essential Guide to HTML5 Using Games to Learn HTML5 and JavaScript Second Edition Jeanine Meyer The Essential Guide to HTML5: Using Games to Learn HTML5 and JavaScript Jeanine Meyer Purchase, NY, USA ISBN-13 (pbk): 978-1-4842-4154-7 ISBN-13 (electronic): 978-1-4842-4155-4 https://doi.org/10.1007/978-1-4842-4155-4 Library of Congress Control Number: 2018962546 Copyright © 2018 by Jeanine Meyer This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Louise Corrigan Development Editor: James Markham Coordinating Editor: Nancy Chen Cover d; esigned by eStudioCalamar Cover image designed by Freepik (www.freepik.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springersbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail rights@apress.com, or visit http://www.apress.com/ rights-permissions. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book's product page, located at www.apress.com/9781484241547. For more detailed information, please visit http://www.apress.com/source-code. Printed on acid-free paper To Annika, Daniel, Aviva, and Anne, and to Esther and Joseph, who are still in our lives Table of Contents About the Author����������������������������������������������������������������������������������������������������� xi About the Technical Reviewer������������������������������������������������������������������������������� xiii Acknowledgments���������������������������������������������������������������������������������������������������xv Introduction�����������������������������������������������������������������������������������������������������������xvii Chapter 1: The Basics����������������������������������������������������������������������������������������������� 1 Introduction����������������������������������������������������������������������������������������������������������������������������������� 1 Critical Requirements������������������������������������������������������������������������������������������������������������������� 4 HTML5, CSS, and JavaScript Features������������������������������������������������������������������������������������������ 4 Basic HTML Structure and Tags����������������������������������������������������������������������������������������������� 4 JavaScript Programming������������������������������������������������������������������������������������������������������� 13 Using a Text Editor���������������������������������������������������������������������������������������������������������������������� 15 Building the Applications������������������������������������������������������������������������������������������������������������ 18 Testing and Uploading the Application���������������������������������������������������������������������������������������� 25 Summary������������������������������������������������������������������������������������������������������������������������������������ 26 Chapter 2: Dice Game��������������������������������������������������������������������������������������������� 27 Introduction��������������������������������������������������������������������������������������������������������������������������������� 27 Critical Requirements����������������������������������������������������������������������������������������������������������������� 30 HTML5, CSS, and JavaScript Features���������������������������������������������������������������������������������������� 31 Pseudo-Random Processing and Mathematical Expressions����������������������������������������������� 31 Variables and Assignment Statements���������������������������������������������������������������������������������� 32 Programmer-Defined Functions�������������������������������������������������������������������������������������������� 34 Conditional Statements: if and switch����������������������������������������������������������������������������������� 36 Drawing on the Canvas���������������������������������������������������������������������������������������������������������� 39 v Table of Contents Building the Application and Making It Your Own����������������������������������������������������������������������� 51 Throwing a Single Die����������������������������������������������������������������������������������������������������������� 53 Throwing Two Dice���������������������������������������������������������������������������������������������������������������� 60 The Complete Game of Craps������������������������������������������������������������������������������������������������ 67 Testing and Uploading the Application���������������������������������������������������������������������������������������� 78 Summary������������������������������������������������������������������������������������������������������������������������������������ 79 Chapter 3: Bouncing Ball���������������������������������������������������������������������������������������� 81 Introduction��������������������������������������������������������������������������������������������������������������������������������� 81 Critical Requirements����������������������������������������������������������������������������������������������������������������� 85 HTML5, CSS, JavaScript Features����������������������������������������������������������������������������������������������� 86 Drawing a Ball or an Image or Images���������������������������������������������������������������������������������� 86 Building the Application and Making It Your Own��������������������������������������������������������������������� 103 Testing and Uploading the Application�������������������������������������������������������������������������������������� 121 Summary���������������������������������������������������������������������������������������������������������������������������������� 122 Chapter 4: Cannonball and Slingshot������������������������������������������������������������������� 123 Introduction������������������������������������������������������������������������������������������������������������������������������� 123 Critical Requirements��������������������������������������������������������������������������������������������������������������� 127 HTML5, CSS, and JavaScript Features�������������������������������������������������������������������������������������� 129 Arrays and Programmer-Defined Objects���������������������������������������������������������������������������� 129 Rotations and Translations for Drawing������������������������������������������������������������������������������� 132 Drawing Line Segments������������������������������������������������������������������������������������������������������ 137 Mouse Events for Pulling on the Slingshot�������������������������������������������������������������������������� 139 Changing the List of Items Displayed Using Array Splice���������������������������������������������������� 141 Distance Between Points����������������������������������������������������������������������������������������������������� 142 Building the Application and Making It Your Own��������������������������������������������������������������������� 143 Cannonball: With Cannon, Angle, and Speed����������������������������������������������������������������������� 150 Slingshot: Using a Mouse to Set Parameters of Flight�������������������������������������������������������� 160 Testing and Uploading the Application�������������������������������������������������������������������������������������� 172 Summary���������������������������������������������������������������������������������������������������������������������������������� 172 vi Table of Contents Chapter 5: The Memory (aka Concentration) Game���������������������������������������������� 175 Introduction������������������������������������������������������������������������������������������������������������������������������� 175 Critical Requirements��������������������������������������������������������������������������������������������������������������� 181 HTML5, CSS, JavaScript Features��������������������������������������������������������������������������������������������� 182 Representing Cards������������������������������������������������������������������������������������������������������������� 183 Using Date for Timing���������������������������������������������������������������������������������������������������������� 184 Providing a Pause���������������������������������������������������������������������������������������������������������������� 185 Drawing Text������������������������������������������������������������������������������������������������������������������������ 186 Drawing Polygons���������������������������������������������������������������������������������������������������������������� 189 Shuffling Cards�������������������������������������������������������������������������������������������������������������������� 190 Implementing Clicking on a Card���������������������������������������������������������������������������������������� 191 Preventing Certain Types of Cheating���������������������������������������������������������������������������������� 192 Building the Application and Making It Your Own��������������������������������������������������������������������� 193 Testing and Uploading the Application�������������������������������������������������������������������������������������� 215 Summary���������������������������������������������������������������������������������������������������������������������������������� 215 Chapter 6: Quiz����������������������������������������������������������������������������������������������������� 217 Introduction������������������������������������������������������������������������������������������������������������������������������� 217 Critical Requirements for a Quiz Game������������������������������������������������������������������������������������� 221 HTML5, CSS, and JavaScript Features�������������������������������������������������������������������������������������� 222 Storing and Retrieving Information in Arrays���������������������������������������������������������������������� 222 Creating HTML During Program Execution�������������������������������������������������������������������������� 225 Using CSS in the Style Element������������������������������������������������������������������������������������������� 227 Responding to Player Moves����������������������������������������������������������������������������������������������� 228 Presenting Audio and Video������������������������������������������������������������������������������������������������� 230 Checking the Player's Answer��������������������������������������������������������������������������������������������� 231 Building the Application and Making It Your Own��������������������������������������������������������������������� 232 Testing and Uploading the Application�������������������������������������������������������������������������������������� 243 Summary���������������������������������������������������������������������������������������������������������������������������������� 243 vii Table of Contents Chapter 7: Mazes�������������������������������������������������������������������������������������������������� 245 Introduction������������������������������������������������������������������������������������������������������������������������������� 245 Critical Requirements��������������������������������������������������������������������������������������������������������������� 253 HTML5, CSS, and JavaScript Features�������������������������������������������������������������������������������������� 254 Representation of Walls and the Token������������������������������������������������������������������������������� 254 Mouse Events to Build and Position a Wall�������������������������������������������������������������������������� 255 Detecting the Arrow Keys���������������������������������������������������������������������������������������������������� 256 Collision Detection: Token and Any Wall������������������������������������������������������������������������������ 258 Using Local Storage������������������������������������������������������������������������������������������������������������� 262 Encoding Data for Local Storage����������������������������������������������������������������������������������������� 270 Radio Buttons���������������������������������������������������������������������������������������������������������������������� 272 Building the Application and Making It Your Own��������������������������������������������������������������������� 273 Creating the Second Maze Application�������������������������������������������������������������������������������� 285 Testing and Uploading Application�������������������������������������������������������������������������������������������� 296 Summary���������������������������������������������������������������������������������������������������������������������������������� 297 Chapter 8: Rock, Paper, Scissors�������������������������������������������������������������������������� 299 Introduction������������������������������������������������������������������������������������������������������������������������������� 299 Critical Requirements��������������������������������������������������������������������������������������������������������������� 303 HTML5, CSS, and JavaScript Features�������������������������������������������������������������������������������������� 304 Providing Graphical Buttons for the Player�������������������������������������������������������������������������� 304 Generating the Computer Move������������������������������������������������������������������������������������������� 310 Starting Off�������������������������������������������������������������������������������������������������������������������������� 321 Building the Application and Making It Your Own��������������������������������������������������������������������� 322 Testing and Uploading the Application�������������������������������������������������������������������������������������� 333 Summary���������������������������������������������������������������������������������������������������������������������������������� 334 viii Table of Contents Chapter 9: Hangman��������������������������������������������������������������������������������������������� 335 Introduction������������������������������������������������������������������������������������������������������������������������������� 335 Critical Requirements��������������������������������������������������������������������������������������������������������������� 343 HTML5, CSS, JavaScript Features��������������������������������������������������������������������������������������������� 344 Storing a Word List as an Array Defined in an External Script File������������������������������������� 345 Generating and Positioning HTML Markup, then Changing the Markup to Buttons, and then Disabling the Buttons����������������������������������������������������������������������������� 346 Creating Progressive Drawings on a Canvas����������������������������������������������������������������������� 349 Maintaining the Game State and Determining a Win or Loss���������������������������������������������� 352 Checking a Guess and Revealing Letters in the Secret Word by Setting textContent��������� 353 Building the Application and Making It Your Own��������������������������������������������������������������������� 354 Testing and Uploading the Application�������������������������������������������������������������������������������������� 368 Summary���������������������������������������������������������������������������������������������������������������������������������� 369 Chapter 10: Blackjack������������������������������������������������������������������������������������������ 371 Introduction������������������������������������������������������������������������������������������������������������������������������� 371 Critical Requirements��������������������������������������������������������������������������������������������������������������� 378 HTML5, CSS, and JavaScript Features�������������������������������������������������������������������������������������� 379 Source for Images for Card Faces and Setting Up the Image Objects��������������������������������� 379 Creating the Programmer-Defined Object for the Cards������������������������������������������������������ 380 Starting a Game������������������������������������������������������������������������������������������������������������������� 381 Dealing the Cards���������������������������������������������������������������������������������������������������������������� 382 Shuffling the Deck��������������������������������������������������������������������������������������������������������������� 387 Capturing Key Presses�������������������������������������������������������������������������������������������������������� 388 Using Header and Footer Element Types����������������������������������������������������������������������������� 390 Building the Application and Making It Your Own��������������������������������������������������������������������� 391 Testing and Uploading the Application�������������������������������������������������������������������������������������� 407 Summary���������������������������������������������������������������������������������������������������������������������������������� 408 Index��������������������������������������������������������������������������������������������������������������������� 409 ix About the Author Jeanine Meyer is slowly moving into retirement from Purchase College/State University of New York, where she now is officially Professor Emirata. She taught and still teaches courses for mathematics/computer science along with general education mathematics courses, the latest being one on origami. The website for her academic activities is http://faculty.purchase.edu/jeanine.meyer and materials are available at http://moodle.purchase.edu. Before coming to academia, she was a Research Staff Member and Manager at IBM Research, working on robotics and manufacturing research and later as a consultant for IBM's educational grant programs. Her first academic job was at Pace University. For Jeanine, programming is both a hobby and a vocation. Every day, she plays computer puzzles online (including Words with Friends, various solitaire card games, and Duolingo for Spanish, which she views as a game). She tries The New York Times crossword puzzle most days, but does better at the mini-puzzle, in which she competes with her children. She also does ken ken. She enjoys cooking, baking, eating, gardening, travel, and a moderate amount of walking. She misses her mother, who inspired both Jeanine and Aviva, her daughter, to take up piano and her father, who gave her a love of puzzles. She is an active volunteer for progressive causes and candidates. xi About the Technical Reviewer Takashi Mukoda is an international student at Purchase College/State University of New York. Now, he is taking a semester off and back home in Japan. At Purchase College, he majors in Mathematics/Computer Science and New Media and has worked as a teaching assistant for computing and mathematics courses. Takashi likes playing the keyboard and going on hikes in the mountains to take pictures. His interest in programming and art incites him to create multimedia art pieces. Some of them are built with Processing and interact with human motion and sounds. (check out his website at http://www.takashimukoda.com) xiii Acknowledgments Much appreciation to my students and colleagues at Purchase College/State University of New York for their inspiration, stimulation, and support; and to family and friends who indulge me in my use of family photos and video clips for my courses and my books. Thanks to the crew at Apress and Springer for all their efforts. xv Introduction There was considerable enthusiasm about the new capabilities of HTML5, and even suggestions that no other technologies or products are necessary to produce dynamic, engrossing, interactive websites. That may be overstating things, but it is true the new features are exciting. HTML is HTML5. It now is possible, using just HTML, Cascading Style Sheets, and JavaScript, to draw lines, arcs, circles, and ovals on the screen and specify events and event handling to produce animation and respond to user actions. You can include video and audio on your website with standard controls, or include the video or audio in your application exactly when and where needed. You can create forms that validate the input and provide immediate feedback to users. You can use a facility similar to cookies to store information on the client computer. And you can use new elements, such as headers and footers, to help structure your documents. This book is based on my teaching practices and past writings. Delving into the features of a technology or general programming concepts is best done when there is a need and a context. Games, especially familiar and simple ones, supply the context and thus the motivation and much of the explanation. When learning a new programming language, one of my first steps is to program the game of craps. Also, if I can build a ballistics simulation with animation, such as the slingshot game, and make a video or audio clip play when a specific condition occurs, I am happy. If I can construct my own maze of walls, draw a stick figure for hangman, and store information on the player's computer, I am ecstatic. And that’s what we do in this book. As you see how to build these simple games, you’ll build your expertise as well. This goal of this book, developed with considerable help from the Apress staff and the technical reviewer, Takashi Mukoda, is to introduce you to programming, with the motivation of implementing games and building websites to share with others. • At the time of updating this book, browser support for HTML5 features is close to complete. The applications have been tested using Chrome, Firefox, and Safari. However, it is important to keep in mind that browsers can change. xvii Introduction • My focus is on plain HTML and JavaScript because it has been my experience that knowledge and experience with the basics is the best introduction. Frameworks and libraries exist and continue to be developed and refined and at some point; these are appropriate to study. The reader can turn to these topics after getting comfortable with the basics. I note that my HTML5 and JavaScript Projects book has been updated and follows this text in complexity. Who Is This Book For? This book is for people who want to learn how HTML, JavaScript, and Cascading Style Sheets can serve to build dynamic, exciting websites. It’s for you if you know something about programming and want to see what the current version of HTML and JavaScript bring to the table. And it’s also for you if you have no programming experience whatsoever. Perhaps you’re a web designer or website owner and you want to know how to make things happen behind the scenes or how to request features from programmers. With this book, we want to showcase the new(er) features of HTML5 and demystify the art of programming. Programming is an art and creating appealing games and other applications requires talent and attention to the audience. However, if you can put together words to form sentences and sentences to form paragraphs, and you have some sense of logic, you can program. How Is This Book Structured? The book consists of 10 chapters, each organized around a familiar game or similar application. There is considerable redundancy in the chapters so you can skip around if you like, though the games do get more complex. Each chapter starts by listing the technical features that will be covered and describing the application. We look first at the critical requirements in a general sense: what do we need to implement the application, independent of any specific technology. We then focus on the features of HTML5, CSS, JavaScript, or general programming methodology that satisfy the requirements. Finally, we examine the implementation of the application in detail. I break out the code line by line in a table, with comments next to each line. In the cases where multiple versions of a game are described, only the new lines of code are annotated. This isn't to deprive xviii Introduction you of information, but to encourage you to see what is similar, what is different, and to demonstrate how you can build applications in stages. It certainly is appropriate to consult the commented programs on an as-needed basis. Each chapter includes suggestions on how to make the application your own, and how to test and upload the application to a website. The summary at the end of each chapter highlights what you’ve learned and what you’ll find ahead. Conventions Used in This Book The applications in this book are HTML documents. The JavaScript is in a script element in the head element and the CSS is in the style element in the head element. The body element contains the static HTML, including any canvas elements. Several examples depend on external image files and one example requires external video files and audio files and another external audio files. Layout Conventions To keep this book as clear and easy to follow as possible, the following text conventions are used throughout: • Code is presented in fixed-width font. • The complete code for each application is presented in table, with the left column holding each statement and the right column holding an explanatory comment. • Pseudo-code is written in italic fixed-width font. • Sometimes code won’t fit on a single line in a book. Where this happens, I use an arrow like this: ➥. So, with the formalities out of the way, let’s get started. xix CHAPTER 1 The Basics In this chapter, we cover • The basic structure of an HTML document • The html, head, title, script, style, body, img, and a elements • A Cascading Style Sheet (CSS) example • A JavaScript code example, using Date and document.write I ntroduction Hypertext Markup Language (HTML) is the language for delivering content on the Web. HTML is not owned by anyone, but is the result of people working in many countries and many organizations to define the features of the language. An HTML document is a text document that you can produce using any text editor. HTML documents contain elements surrounded by tags—text that starts with a < symbol and ends with a > symbol. An example of a tag is <img src="home.gif"/>. This particular tag will display the image held in the file home.gif. These tags are the markup. It is through the use of tags that hyperlinks, images, and other media are included in web pages. Basic HTML can include directives for formatting in a language called Cascading Style Sheets (CSS) and programs for interaction in a language called JavaScript. Browsers, such as Firefox and Chrome, interpret the HTML along with any CSS and JavaScript to produce what we experience when we visit a website. HTML holds the content of the website, with tags providing information on the nature and structure of the content as well as references to images and other media. CSS specifies the formatting. The same content can be formatted in different ways. JavaScript is a programming language that’s used to make the website dynamic and interactive. In all but the smallest working groups, different people may be responsible for the HTML, CSS, © Jeanine Meyer 2018 J. Meyer, The Essential Guide to HTML5, https://doi.org/10.1007/978-1-4842-4155-4_1 1 Chapter 1 The Basics and JavaScript, but it’s always a good idea to have a basic understanding of how these different tools work together. If you are already familiar with the basics of HTML and how CSS and JavaScript can be added together, you may want to skip ahead to the next chapter. Still, it may be worth casting your eye over the content in this chapter, to make sure you are up to speed on everything before we start on the first core examples. The latest version of HTML (and its associated CSS and JavaScript) is HTML5. It has generated considerable excitement because of features such as the canvas for displaying pictures and animation; support for video and audio; and tags for defining common document elements such as header, section, and footer. You can create a sophisticated, highly interactive website with HTML5. As of this writing, not all browsers accept all the features, but you can get started learning HTML5, CSS, and JavaScript now. Learning JavaScript will introduce you to general programming concepts that will be beneficial if you try to learn any other programming language or if you work with programmers as part of a team. The approach I’ll use in this book is to explain HTML5, CSS, and JavaScript concepts in the context of specific examples, most of which will be familiar games. Along the way, I’ll use small examples to demonstrate specific features. Hopefully, this will help you both understand what you want to do and appreciate how to do it. You will know where we are headed as I explain the concepts and details. The task for this chapter is to build a web page of links to other websites. In this way, you’ll get a basic understanding of the structure of an HTML document, with a small amount of CSS code and JavaScript code. For this and other examples, please think of how to make the project meaningful to you. The page could be a list of your own projects, favorite sites, or sites on a particular topic. For each site, you’ll see text and a hyperlink. The second example includes some extra formatting in the form of boxes around the text, pictures, and the day’s date and time. Figure 1-1 and Figure 1-2 show the different examples I’ve created. 2 Chapter 1 The Basics Figure 1-1. An annotated list of games Figure 1-2. Favorite sites, with extra formatting 3 Chapter 1 The Basics When you reload the Favorite Sites page, the date and time will change to the current date and time according to your computer. C ritical Requirements The requirements for the list of links application are the very fundamental requirements for building a web page containing text, links, and images. For the example shown in Figure 1-1, each entry appears as a paragraph. In the example shown in Figure 1-2, in contrast, each entry has a box around it. The second example also includes images and a way to obtain the current day, date, and time. Later applications will require more discussion, but for this one we’ll go straight to how to implement it using HTML, CSS, and JavaScript. HTML5, CSS, and JavaScript Features As I noted, HTML documents are text, so how do we specify links, pictures, formatting, and coding? The answer is in the markup, that is, the tags. Along with the HTML that defines the content, you’ll typically find CSS styles, which can be specified either inside the HTML document or in an external document. You might also include JavaScript for interactivity, again specified in the HTML document or in an external document. We’ll start with a look at how you can build simple HTML tags, and how you can add inline CSS and JavaScript all within the same document. Basic HTML Structure and Tags An HTML element begins with a starting tag, which is followed by the element content and an ending tag. The ending tag includes a / symbol followed by the element type, for example /head. Elements can be nested within elements. A standard HTML document looks like this: <html> <head> <title>Very simple example </title> </head> 4 Chapter 1 The Basics <body> This will appear as is. </body> </html> Note that I’ve indented the nested tags here to make them more obvious, but HTML itself ignores this indentation (or whitespace, as it’s known), and you don’t need to add it to your own files. In fact, for most of the examples throughout this book, I don’t indent my code. This document consists of the html element, indicated by the starting tag <html> and ending with the closing tag: </html>. HTML documents typically have a head and a body element, as this one has. This head element contains one element, title. The HTML title shows up different places in different browsers. Figure 1-3 shows the title, “Very Simple Example”, on a tab in Firefox. Figure 1-3. The HTML title on a tab in Firefox browser In most cases, you will create something within the body of the web page that you’ll think of as a title, but it won’t be the HTML title! Figure 1-3 also shows the body of the web page: the short piece of text. Notice that the words html, head, title, and body do not appear. The tags “told” the browser how to display the HTML document. We can do much more with text, but let’s go on to see how to get images to appear. This requires an img element. Unlike the html, head, and body elements that use starting and ending tags, the img element just uses one tag. It is called a singleton tag. Its element type is img (not image) and you put all the information with the tag itself using what are 5 Chapter 1 The Basics termed attributes. What information? The most important item is the name of the file that holds the image. The tag <img src="frog.jpg"/> tells the browser to look for a file with the name frog and the file type .jpg. In this case, the browser looks in the same directory or folder as the HTML file. You can also refer to image files in other places and I’ll show this later. The src stands for source. It is termed an attribute of the element. The slash before the > indicates that this is a singleton tag. There are common attributes for different element types, but most element types have additional attributes. Another attribute for img elements is the width attribute. <img src="frog.jpg" width="200"/> This specifies that the image should be displayed with a width of 200 pixels. The height will be whatever is necessary to keep the image at its original aspect ratio. If you want specific widths and heights, even if that may distort the image, specify both width and height attributes. Tip You’ll see examples (maybe even some of mine) in which the closing slash is missing that work just fine. It is considered good practice to include it. Similarly, you’ll see examples in which there are no quotation marks around the name of the file. HTML is more forgiving in terms of syntax (punctuation) than most other programming systems. Finally, you’ll see HTML documents that start with a tag of type!DOCTYPE and have the HTML tag include other information. At this point, we don’t need this so I will keep things as simple as I can (but no simpler, to quote Einstein). Producing hyperlinks is similar to producing images. The type of element for a hyperlink is a and the important attribute is href. <a href="http://faculty.purchase.edu/jeanine.meyer">Jeanine Meyer's Academic Activities </a> As you can see, this element has a starting and ending tag. The content of the element, whatever is between the two tags—in this case, Jeanine Meyer’s Academic Activities—is what shows up in blue and underlined. The starting tag begins with a. One way to remember this is to think of it as the most important element in HTML, so 6 Chapter 1 The Basics it uses the first letter of the alphabet. You can also think of an anchor, which is what the a actually stands for, but that isn’t as meaningful for me. The href attribute (think hypertext reference) specifies the website where the browser goes when the hyperlink is clicked. Notice that this is a full web address (called a Universal Resource Locator, or URL, for short). Web addresses can be absolute or relative. An absolute address starts with http://. A relative address is relative to the location of the HTML file. Using relative addressing makes it easier to move your project to a different website and you can indicate the folder one level up by using ../. In my example, the frog.gif file, frogface.gif file, and other image files are located in the same folder as my HTML file. They are there because I put them there! For large projects, many people put all the images in a subfolder called images and write addresses as images/postcard.gif. File management is a big part of creating web pages. We can combine a hyperlink element with an img element to produce a picture on the screen that a user can click on. Remember that elements can be nested within other elements. Instead of putting text after the starting <a> tag, put an <img> tag: <a href="http://faculty.purchase.edu/jeanine.meyer"> <img src="jhome.gif" width="100" /> </a> Let’s put these examples together now: <html> <head> <title>Second example </title> </head> <body> This will appear as is. <img src="frog.gif"/> <img src="frog.gif" width="200"/> <a href=http://faculty.purchase.edu/jeanine.meyer>Jeanine Meyer's Academic Activities </a> <a href=http://faculty.purchase.edu/jeanine.meyer><img src="jhome.gif"/></ a> </body> </html> 7 Chapter 1 The Basics I created the HTML file, saved it as second.html, and then opened it in the Chrome browser. Figure 1-4 shows what is displayed. Figure 1-4. Example with images and hyperlinks This produces the text; the image in its original width and height; the image with the width fixed at 200 pixels and height proportional; a hyperlink that will take you to my web page (I promise); and another link that uses an image that will also take you to my web page. However, this isn’t quite what I had in mind. I wanted these elements spaced down the page. This demonstrates something you need to remember: HTML ignores line breaks and other whitespace. If you want a line break, you have to specify it. One way is to use the br singleton tag. I’ll show other ways later. Take a look at the following modified code. Notice that the <br/> tags don’t need to be on a line by themselves. <html> <head> <title>Second example </title> </head> <body> This will appear as is. <br/> <img src="frog.gif"/> <br/> <img src="frog.gif" width="200"/> <br/> <a href=http://faculty.purchase.edu/jeanine.meyer>Jeanine Meyer's Academic Activities </a> <br/> 8 Chapter 1 The Basics <a href=http://faculty.purchase.edu/jeanine.meyer><img src="jhome.gif"/></ a> </body> </html> Figure 1-5 shows what this code produces. Figure 1-5. Text, images, and links with line breaks There are many HTML element types: the h1 through h6 heading elements produce text of different sizes; there are various elements for lists and tables, and others for forms. CSS, as we’ll see in a moment, is also used for formatting. You can select different fonts, 9 Chapter 1 The Basics background colors, and colors for the text, and control the layout of the document. It’s considered good practice to put formatting in CSS, interactivity in JavaScript, and keep the HTML for the content. HTML5 provides new structural elements—such as article, section, footer, and header—putting formatting into the style element and making use of the new elements, called semantic tags, facilitates working with other people. However, even when you’re working just with yourself, separating content, formatting, and behavior lets you easily change the formatting and the interactions. Formatting, including document layout, is a large topic. In this book, I stick to the basics. Using Cascading Style Sheets CSS is a special language just for formatting. A style is essentially a rule that specifies how a particular element will be formatted. This means you can put style information in a variety of places: a separate file, a style element located in the head element, or a style within the HTML document, perhaps within the one element you want to format in a particular way. The styling information cascades, trickles down, unless a different style is specified. To put it another way, the style closest to the element is the one that’s used. For example, you might use your official company fonts as given in the style section in the head element to flow through most of the text, but include specification within the local element to style one particular piece of text. Because that style is closest to the element, it is the one that is used. The basic format includes an indicator of what is to be formatted followed by one or more directives. In the examples for this chapter, I’ll specify the formatting for elements of type section, namely a border or box around each item, margins, padding, and alignment, and a background of white. The complete HTML document in Listing 1-1 is a mixture (some would say a mess!) of features. The elements body and p (paragraph) are part of the original version of HTML. The section element is one of the new element types added in HTML5. The section element does need formatting, unlike body and p, which have default formatting that the body and each p element will start on a new line. CSS can modify the formatting of old and new element types. Notice that the background color for the text in the section is different from the background color for the text outside the section. In the code in Listing 1-1, I specify styles for the body element (there is just one) and the section element. If I had more than one section element, the styling would apply to each of them. The style for the body specifies a background color and a color for the text. In the beginning, browsers accepted a set of only 16 colors by name, including black, 10 Chapter 1 The Basics white, red, blue, green, cyan, and pink. However, now the up-to-date browsers accept 140 colors by name. See https://www.w3schools.com/colors/colors_names.asp. You can also specify color using RGB (red green blue) hexadecimal codes, but you’ll need to use a graphics program—such as Adobe Photoshop, Corel Paint Shop Pro, or Adobe Flash Professional—to figure out the RGB values, or you can experiment. I used Paint Shop Pro to determine the RGB values for the green in the frog head picture and used that for the border as well. The text-align directives are just what they sound like: they indicate whether to center the material or align it to the left. The font-size sets the size of text in pixels. Borders are tricky and don’t appear to be consistent across browsers. Here I’ve specified a solid green border of 4 pixels. The width specification for section indicates that the browser should use 85 percent of the window, whatever that is. The specification for p sets the width of the paragraph at 250 pixels. Padding refers to the spacing between the text and the borders of the section. The margin is the spacing between the section and its surroundings. Listing 1-1. A Complete HTML Document with Styles <html> <head> <title>CSS example </title> <style> body { background-color:tan; color: #EE015; text-align:center; font-size:22px; } section { width:85%; border:4px #00FF63 solid; text-align:left; padding:5px; margin:10px; background-color: white; } 11 Chapter 1 The Basics p { width: 250px; } </style> </head> <body> The background here is tan and the text is the totally arbitrary RED GREEN BLUE➥ value #EE1055<br/> <section>Within the section, the background color is white. There is text with➥ additional HTML markup, followed by a paragraph with text. Then, outside the➥ section there will be text, followed by an image, more text and then a➥ hyperlink. <p>The border color of the section matches the color of the➥ frog image. </p></section> <br/> As you may have noticed, I like origami. The next image represents a frog head.<br/> <img src="frogface.gif"/> <br/>If you want to learn how to fold it, go to <a href=http://faculty.purchase.edu/jeanine.meyer/origami>the Meyer Family➥ Origami Page <img src="crane.png" width="100"/></a> </body> </html> This produces the screen shown in Figure 1-6. 12 Chapter 1 The Basics Figure 1-6. Sample CSS styles Tip Don’t be concerned if you don’t understand everything immediately. Modify these examples and make up your own. You’ll find lots of help on the Web. In particular, see the official source for HTML 5 at http://dev.w3.org/html5/ spec/Overview.html. There are many things you can do with CSS. You can use it to specify formatting for types of elements, as shown here; you can specify that elements are part of a class; and you can identify individual elements using the id attribute. In Chapter 6, where we create a quiz, I use CSS to position specific elements in the window and then JavaScript to move them around. J avaScript Programming JavaScript is a programming language with built-in features for accessing parts of an HTML document, including styles in the CSS element. It is termed a scripting language to distinguish it from compiled languages, such as C++. Compiled languages are translated all at once, prior to use, while scripting languages are interpreted line by line by browsers. This text assumes no prior programming experience or knowledge of JavaScript, but it may help to consult other books, such as Getting Started with JavaScript, by Terry McNavage (friends of ED, 2010), or online sources such as http:// en.wikipedia.org/wiki/JavaScript. Each browser owns its version of JavaScript. 13 Chapter 1 The Basics An HTML document holds JavaScript in a script element, located in the head element. To display the time and date information as shown in Figure 1-2, I put the following in the head element of the HTML document: <script> document.write(Date()); </script> JavaScript, like other programming languages, is made up of statements of various types. In later chapters, I’ll show you assignment statements, compound statements such as if and switch and for statements, and statements that create what are called programmer-defined functions. A function is one or more statements that work together in a block and can be called any time you need that functionality. Functions save writing out the same code over and over. JavaScript supplies many built-in functions. Certain functions are associated with objects (more on this later) and are called methods. The code document.write("hello"); is a JavaScript statement that invokes the write method of the document object with the argument "hello". An argument is additional information passed to a function or method. Statements are terminated by semicolons. This piece of code will write out the literal string of characters h, e, l, l, o as part of the HTML document. The document.write method writes out anything within the parentheses. Since I wanted the information written out to change as the date and time change, I needed a way to access the current date and time, so I used the built-in JavaScript Date function. This function produces an object with the date and time. Later, you’ll see how to use Date objects to compute how long it takes for a player to complete a game. For now, all I want to do is display the current date and time information, and that’s just what this code does: document.write(Date()); To use the formal language of programming: this code calls (invokes) the write method of the document object, a built-in piece of code. The period (.) indicates that the write to be invoked is a method associated with the document produced by the HTML file. So, something is written out as part of the HTML document. What is written out? Whatever is between the opening parenthesis and the closing parenthesis. And what 14 Chapter 1 The Basics is that? It is the result of the call to the built-in function Date. The Date function gets information maintained by the local computer and hands it off to the write method. Date also requires the use of parentheses, which is why you see so many. The write method displays the date and time information as part of the HTML document, as shown in Figure 1-2. The way these constructs are combined is typical of programming languages. The statement ends with a semicolon. Why not a period? A period has other uses in JavaScript, such as indicating methods and serving as a decimal point for numbers. Natural languages, such as English, and programming languages have much in common—different types of statements; punctuation using certain symbols; and grammar for the correct positioning of elements. In programming, we use the term notation instead of punctuation, and syntax instead of grammar. Both programming languages and natural languages also let you build up very complex statements out of separate parts. However, there is a fundamental difference: As I tell my students, chances are good that much of what I say in class is not grammatically correct, but they’ll still understand me. But when you’re “talking” to a computer via a programming language, your code must be perfect in terms of the grammatical rules of the language to get what you want. The good news is that unlike a human audience, computers do not exhibit impatience or any other human emotion so you can take the time you need to get things right. There’s also some bad news that may take you a while to appreciate. If you make a mistake in grammar—termed a syntactic error—in HTML, CSS, or JavaScript, the browser still tries to display something. It’s up to you figure out what and where the problem is when you don’t get the results you wanted in your work. Using a Text Editor You build an HTML document using a text editor and you view/test/play the document using a browser. Though you can use any text editor program to write the HTML, I suggest TextPad for PCs and Sublime for Macs. These are shareware, which makes them relatively inexpensive. Don’t use a word processing program, which may insert non-text characters. Notepad also works, although the other tools have benefits such as color- coding that I’ll demonstrate. To use the editor, you open it and type in the code. Figure 1-7 shows what the Sublime screen looks like. 15 Chapter 1 The Basics Figure 1-7. Starting off in Sublime You will want to save your work frequently and, most important, save it as the file type.html. Do this at the start and then you will gain the benefits of the color-coding. In Sublime, click on File ➤ Save As and then enter the name with the file extension .html, as shown in Figure 1-8. 16 Chapter 1 The Basics Figure 1-8. Saving a file as type HTML Notice that I gave the file a name and a file extension and that I also specified the folder where I want the file to reside. After saving the file, the window appears as shown in Figure 1-9, with color coding. 17 Chapter 1 The Basics Figure 1-9. After saving the file as HTML The color coding, which you’ll see only after the file is saved as HTML, indicates tags and quoted strings. This can be valuable for catching many errors. Sublime and the other editors do provide options for changing the color scheme. Assuming that you are using the one shown here, if you see long sections of yellow, the color for quoted strings, it probably means a missing closing quotation marks. By the way, you can use single or double quotation marks but you can’t mix them up. Also, if you copy and paste from Word or PowerPoint, and copy so-called “smart” quotation marks, ones that curve, this will cause problems. B uilding the Applications You can examine the source code for the following applications at ????. The source code for an HTML document typically includes an HTML document and other files. • 18 The verysimple.html file is complete in itself and was shown in Figure 1-3. Chapter 1 • The second.html application was shown in Figure 1-4. Two image files are referenced: frog.gif two times and jhome.gif one time. • The third.html, with the garish colors, references two image files: frogface.gif and crane.gif. • The games.html file is complete in itself in that it does not reference any image files. If the files mentioned in the href attributes of the a tags are not present, then there will be error messages when the hyperlinks are clicked. • The ch01FavoriteSites.html file references two image files: avivasmugmug.jpeg and apressshot.jpeg. The Basics Keeping track of files is a critical part of building HTML applications. Now let’s delve into the HTML coding, first for the list of annotated links describing games and then for the favorite sites. The code uses the features described in the previous section. Table 1-1 shows the complete code that produced the display shown in Figure 1-1: paragraphs of text with links to different files, all located in the same folder. Table 1-1. The “My Games” Annotated Links Code Code Explanation <html> Opening html tag. <head> Opening head tag. <title>Annotated links</title> Opening title tag, the title text, and closing title tag. </head> <body> Opening body tag. <h1>My games</h1> Opening h1 tag, text and then closing h1 tag. This will make “My Games” appear in a big font. The actual font will be the default. <p> Opening p for paragraph tag. (continued) 19 Chapter 1 The Basics Table 1-1. (continued) Code Explanation The <a href="craps.html">Dice game</ Text with an a element. The opening a tag has a> presents the game called craps. the attribute href set to the value craps.html. Presumably this is a file in the same folder as this HTML file. The contents of the a element— whatever is between the <a> and the </a>—will be displayed, first in blue and then in mauve once clicked, and underlined. </p> Closing p tag. <p> Opening p tag. The <a href="cannonball.html"> See the previous case. The a element here refers Cannonball</a> is a ballistics to the cannonball.html file and the displayed simulation. A ball appears to move text is Cannonball. on the screen in an arc. The program determines when the ball hits the ground or the target. The player can adjust the speed and the angle. </p> Closing p tag. <p> Opening p tag. The <a href="slingshot. html">Slingshot</a> simulates shooting a slingshot. A ball moves on the screen, with the angle and speed depending on how far the player has pulled back on the slingshot using the mouse. See previous. This paragraph contains the hyperlink to slingshot.html. </p> Closing p tag. <p> Opening p tag. (continued) 20 Chapter 1 The Basics Table 1-1. (continued) Code Explanation The <a href="memory. See previous. This paragraph contains the html">Concentration/memory game</a> hyperlink to memory.html. presents a set of plain rectangles you can think of as the backs of cards. The player clicks on first one and then another and pictures are revealed. If the two pictures represent a match, the two cards are removed. Otherwise, the backs are displayed. The game continues until all matches are made. The time elapsed is calculated and displayed. </p> Closing p tag. <p> Opening p tag. The <a href="quiz1.html">Quiz See previous. This paragraph contains the game</a> presents the player with hyperlink to quiz1.html. 4 boxes holding names of countries and 4 boxes holding names of capital cities. These are selected randomly from a larger list. The player clicks to indicate matches and the boxes are moved to put the guessed boxes together. The program displays whether or not the player is correct. </p> Closing p tag. <p> Opening p tag. (continued) 21 Chapter 1 The Basics Table 1-1. (continued) Code Explanation The <a href="maze.html">Maze</a> program is a multi-stage game. The player builds a maze by using the mouse to build walls. The player then can move a token through the maze. The player can also save the maze on the local computer using a name chosen by the player and retrieve it later, even after closing the browser or turning off the computer. See previous. This paragraph contains the hyperlink to maze.html. </p> Closing p tag. </body> Closing body tag. </html> Closing html tag. Once you have created several of your own HTML applications, you may build a document such as this one to serve as your own annotated list. If you use folders, the href links will need to reflect the location in terms of the HTML document. The Favorite Sites code has the features of the annotated list with the addition of formatting: a green box around each item and a picture in two of the three items. See Table 1-2. 22 Chapter 1 The Basics Table 1-2. The Favorites Sites Code Code Explanation <html> Opening html tag. <head> Opening head tag. <title>Annotated links</title> Complete title element: opening and closing tag and Annotated links in between. <style> Opening style tag. This means we’re now going to use CSS. article { Start of a style. The reference to what is being styled is all article elements. The style then has a brace - {. The opening and closing braces surround the style rule we’re creating, much like opening and closing tags in HTML. width:60%; The width is set to 60% of the containing element. Note that each directive ends with a ; (semicolon). text-align:left; Text is aligned to the left. margin:10px; The margin is 10 pixels. border:2px green double; The border is a 2-pixel green double line. padding:2px; The space between the text and the border is 2 pixels. display:block; The article is a block, meaning there are line breaks before and after. } Closes the style for article. img {display:block;} Style img elements to block style: line break before and after. </style> Closing style tag. <script> Opening script tag. We are now writing JavaScript code. document.write(Date()); One statement of code: write out what is produced by the Date() call. (continued) 23 Chapter 1 The Basics Table 1-2. (continued) Code Explanation </script> Closing script tag. </head> <body> Opening body tag. <h3>Favorite Sites</h3> Text surrounded by h3 and /h3 tags. This makes the text appear somewhat larger than the norm. <article> Opening article tag. The <a href="http://faculty. This text will be subject to the style specified. It purchase.edu/jeanine.meyer"Jeanine includes an a element. Meyer's Academic Activities</ a> site displays information on my current and past courses, along with publications and other activities. </article> Closing article tag. <article> Opening article tag. The <a href="https://avivameyer. smugmug.com/">Aviva Meyer's photographs</a> site is a collection of Aviva's photographs stored on a site called smugmug. The categories are Music, Adventures and Family (which requires a password). This article is similar to the previous one, with an a element and some text. <img src="avivasmugmug.jpeg" width="300"/> An img tag. The source of the image is the file avivasmugmug.jpeg. If the file had a ,jpg extension, this would not work.The width is set at 300 pixels. There are line breaks before and afterwards because of the style directive in the style section. (continued) 24 Chapter 1 The Basics Table 1-2. (continued) Code Explanation </article> Closing article tag. <article> Opening article tag. <a href="http://apress.com">Apress This is similar to the previous article: an a element publishers</a> is the site for the and some text. publishers of this book. <br/> <img src="apressshot.jpeg" width="300"/> An img element. The source is apressshot.jpeg. The width is set at 300 pixels. </article> Closing article tag. </body> Closing body tag. </html> Closing html tag. It is pretty straightforward how to make this application your own: use your own favorite sites! In most browsers, you can download and save image files if you want to use a site logo for the hyperlink, or you can include other pictures. It is my understanding that making a list of sites with comments and including images such as logos is within the practice called “fair use,” but I am not a lawyer. For the most part, people like links to their sites. It doesn’t affect the legal question, but you can also choose to set the src in the img tag to the web address of the site where the image lives if you’d rather not download a particular image file to your computer and then upload it to your website. You also can make this application your own by changing the formatting. Styles can be used to specify fonts, including specific font, font family, and size. This lets you pick a favorite font and specify what font to use if the preferred font is not available on the user’s computer. You can specify the margin and padding or vary independently the margin-top, margin-left, padding-top, and so forth. Testing and Uploading the Application You need to have all the files, in this case the single HTML file plus all image files, in the same folder unless you are using full web addresses. For the links to work, you need to have the correct addresses for all href attributes. My examples show how to do this for HTML files in the same folder or for HTML files somewhere else on the Web. 25 Chapter 1 The Basics You can start testing your work even if it is not completely done. For example, you can put in a single img element or a single a element. Open up a browser, such as Firefox, Chrome, or Safari. In Firefox, click on File and then Open file and browse to your HTML file. In Chrome, press Ctrl on the PC (CMD on the MAC) and o and then browse to the file and click OK to open it. You should see something like my examples. Click on the hyperlinks to get to the other sites. Reload the page using the reload icon for the browser and observe the different time. If you don’t see what you expect— something like my examples—you need to examine your code. Common mistakes are: • Missing or mismatched opening and closing tags. • Wrong name for image files or HTML files, or wrong file extension for the image files. You can use image files of type JPG, GIF, or PNG, but the file extension named in the tag must match the actual file type of the image. • Missing quotation marks. The color coding, as available in the editors, can help you identify this. Summary In this chapter, you learned how to compose HTML documents with text, images, and hyperlinks. This included: • The basic tags, including html, head, title, style, script, body • The img element for displaying images • The a element for hyperlinks • Simple formatting using a style element written following Cascading Style Sheet (CSS) rules • A single line of JavaScript code to provide date and time information This chapter was just the beginning, though it’s possible to produce beautiful and informative web pages using basic HTML, with or without Cascading Style Sheets. In the next chapter, you learn how to include randomness and interactivity in an application, and how to use the Canvas element, the critical feature of HTML5. 26 CHAPTER 2 Dice Game In this chapter, we cover • Drawing on canvas • Random processing • Game logic • Form output I ntroduction Among the most important new features in HTML5 is the canvas element. This element provides a way for developers to make line drawings, include images, and position text in a totally free-form fashion, a significant improvement over the older HTML. Although you could do some fancy formatting in the earlier versions, layouts tended to be boxy and pages less dynamic. How do you draw on the canvas? You use a scripting language, usually JavaScript. I will show you how to draw on canvas and I’ll explain the important features of JavaScript that we’ll need to build an implementation of the dice game called craps: how to define a function, how to invoke what is termed pseudo-random behavior, how to implement the logic of this particular game, and how to display information to a player. Before we go any further, though, you need to understand the basics of the game. The game of craps has the following rules: The player throws a pair of dice. The sum of the two top faces is what matters so a 1 and a 3 is the same as 2 and 2. The sum of two 6-sided dice can be any number from 2 to 12. If the player throws a 7 or 11 on the first throw, the player wins. If the player throws a 2, 3, or 12, the player loses. For any other result (4, 5, 6, 8, 9, 10), this result is recorded as what is called the player’s point and a follow-up throw is required. On follow-up throws, a throw of 7 loses and a throw of the player’s point wins. For anything else, the game continues with the follow-up throw rules. © Jeanine Meyer 2018 J. Meyer, The Essential Guide to HTML5, https://doi.org/10.1007/978-1-4842-4155-4_2 27 Chapter 2 Dice Game Let’s see what our game play might look like. Figure 2-1 shows the result of a throw of two ones at the start of the game. Figure 2-1. First throw, resulting in a loss for the player It is not apparent here, but our dice game application draws the die faces each time using the canvas tag. This means it’s not necessary to download images of individual die faces. A throw of two 1s means a loss for the player since the rules define 2, 3, or 12 on a first throw as a loss. The next example shows a win for the player, a 7 on a first throw, as shown in Figure 2-2. Figure 2-2. A 7 on a first throw means the player wins 28 Chapter 2 Dice Game Figure 2-3 shows the next throw—an 8. This is neither a win nor a loss, but means there must be a follow-up throw. Figure 2-3. An 8 means a follow-up throw with a player’s point of 8 carried over Let’s assume that the player eventually throws an 8 again, as indicated in Figure 2-4. Figure 2-4. It’s another throw of 8, the point value, so the player wins 29 Chapter 2 Dice Game As the previous sequence shows, the only thing that counts is the sum of the values on the faces of the dice. The point value was set with two 4s, but the game was won with a 2 and a 6. The rules indicate that a game will not always take the same number of throws of the dice. The player can win or lose on the first throw, or there may be any number of follow- up throws. It is the game builder’s job to build a game that works—and working means following the rules, even if that means play goes on and on. My students sometimes act as if their games work only if they win. In a correct implementation of the game, players will win and lose. Critical Requirements The requirements for building the dice game begin with simulating the random throwing of dice. At first, this seems impossible since programming means specifying exactly what the computer will do. Luckily, JavaScript, like most other programming languages, has a built-in facility that produces results that appear to be random. Sometimes languages use the middle bits (1s and 0s) of a very long string of bits representing the time in milliseconds. The exact method isn’t important to us. We will assume that the JavaScript furnished by the browser does an okay job with this, which is called pseudo-random processing. Assuming now that we can randomly get any number from 1 to 6 and do it twice for the two die faces, we need to implement the rules of the game. This means we need a way to keep track of whether we are at a first throw or a follow-up throw. The formal name for this is the application state, which means the way things are right now, and is important in both games and other types of applications. Then we need to use constructs that make decisions based on conditions. Conditional constructs such as if and switch are a standard part of programming languages, and you’ll soon understand why computer science teachers like me—who have never been in a casino or a back alley—really like the game of craps. We need to give the player a way to throw the dice, so we’ll implement a button on the screen to click for that. Then we need to provide information back to the player on what happened. For this application, I produced graphical feedback by drawing dice faces on the screen and also displayed information as text to indicate the stage of the game, the point value, and the result. The older term for interactions with users was input-output (I/O), back when that interaction mainly involved text. The term graphical 30 Chapter 2 Dice Game user interface (GUI) is now commonly used to indicate the vast variety of ways that users interact with computer systems. These include using the mouse to click on a specific point on the screen or combining clicks with dragging to simulate the effect of moving an object (see the slingshot game in Chapter 4). Drawing on the screen requires the use of a coordinate system to specify points. Coordinate systems for the computer screen are implemented in similar ways in most programming languages, as I’ll explain shortly. HTML5, CSS, and JavaScript Features Let’s now take a look at the specific features of HTML5, CSS, and JavaScript that provide what we need to implement the craps game. seudo-Random Processing and Mathematical P Expressions Pseudo-random processing in JavaScript is performed using a built-in method called Math.random. Formally, random is a method of the Math class. The call Math.random() generates a number from 0 up to, but not including 1, resulting in a decimal number, for example, 0.253012. This may not seem immediately useful for us, but it’s actually a very simple process to convert that number into one we can use. We multiply that number, whatever it is, by 6, which produces a number from 0 up to but not including 6. For example, if we multiply the .253012 by 6 we get 1.518072. That’s almost what we need, but not quite. The next step is to strip away the fraction and keep the whole number. To do that, we use another Math method, Math.floor. This method produces a whole number after removing any fractional part. As the name suggests, the floor method rounds down. In our particular case, we started with .253012, then arrived at 1.518072, and, therefore, made the call Math.floor(1.58072) with the result the whole number 1. In general, when we multiply our random number by 6 and floor it, we’ll get a number from 0 to 5. The final step is to add a 1, because our goal is to get a number from 1 to 6, over and over again, with no particular pattern. You can use a similar approach to get whole numbers in any range. For example, if you want the numbers 1 to 13, you’d multiply the random number by 13 and then add 1. This could be useful for a card game. You’ll see similar examples throughout this book. We can combine all of these steps together into what is called an expression. Expressions are combinations of constants, methods, and function calls, and some 31 Chapter 2 Dice Game things we’ll explore later. We put these items together using operators, such as + for addition and * for multiplication. Remember from Chapter 1 how tags can be combined—nesting a tag within another tag—and the one line of JavaScript code we used in the Favorite Sites application: document.write(Date()); We can use a similar process here. Instead of having to write the random call and then the floor method as separate statements, we can pass the random call as an argument of the floor method. Take a look at this code fragment: 1+Math.floor(Math.random()*6) This expression will produce a number from 1 to 6. I call it a code fragment because it isn’t quite a statement. The operators + and * refer to the arithmetic operations and are the same as you’d use in normal math. The order of operations starts from the inside and works out. 1. Invoke Math.random() to get a decimal number from 0 up to, but not quite, 1. 2. Multiply the result by 6. 3. Take that and strip away the fraction, leaving the whole number, using Math.floor. 4. Add 1. You’ll see a statement with this expression in our final code, but we need to cover a few other things first. Variables and Assignment Statements Like other programming languages, JavaScript has a construct called a variable, which is essentially a place to put a value, such as a number. It is a way of associating a name with a value. You can use the value later by referencing the name. One analogy is to office holders. In the US, we speak of “the president.” In 2010, when I worked on the first edition of this book, the president was Barack Obama. Now (July 2018), the president is Donald Trump. The value held by the term “the president” changes. In programming, the value of the variable can vary as well, hence the name. The term var is used to declare a variable. 32 Chapter 2 Dice Game The names of variables and functions, described in the next section, are up to the programmer. There are rules, including no internal blanks, no use of a period, and the name must start with an alphabetic character. There is a limit on the length of a name, but our inclination is to make names short to avoid typing. However, I advise you to not make them so short that you forget what they are. You do need to be consistent, but you don’t need to obey the rules of English spelling. For example, if you want to set up a variable to hold the sum of values and you believe that sum is spelled som, that’s fine. Just make sure you use som all the time. But if you want to refer to something that’s a part of JavaScript, such as function or document or random, you need to use the spelling that JavaScript expects. You should avoid using the names of built-in constructs in JavaScript (such as random or floor) for your variables. Try to make the names unique, but still easily understandable. One common method of writing variable names is to use what’s called camel case. This involves starting your variable name in lowercase, then using a capital letter to denote when a new word starts, for example, numberOfTurns or userFirstThrow. You can see why it’s called camel case—the capitals form “humps” in the word. You don’t have to use this naming method, but it’s a convention many programmers follow. The line of code that will hold the pseudo-random expression explained in the previous section is a particular type of statement called an assignment statement. For example, var ch = 1+Math.floor(Math.random()*6); sets the variable named ch to the value that is the result of the expression on the right side of the equals sign. When used in a var statement, it also would be termed an initialization statement. The = symbol is used for setting initial values for variables as in this situation and in the assignment statements to be described next. I chose to use the name ch as shorthand for choice. This is meaningful for me. In general, though, if you need to choose between a short name and a longer one that you will remember, pick the longer one! Notice that the statement ends with a semicolon. You may ask, why not a period? The answer is that a period is used in two other situations: as a decimal point and for accessing methods and properties of objects, as in document.write. Assignment statements are the most common type of statements in programming. Here’s an example of an assignment statement for a variable already defined: bookname = "The Essential Guide to HTML5"; 33 Chapter 2 Dice Game The use of the equals sign may be confusing. Think of it as making it true that the left side equals what’s produced by the right side. You’ll encounter many other variables and other uses of operators and assignment statements in this book. Caution The var statement defining a variable is called a declaration statement. JavaScript, unlike many other languages, allows programmers to omit declaration statements and just start using a variable. I try to avoid doing that, but you will see it in many online examples. For the game of craps, we need variables that define the state of the game, namely whether it is a first throw or a follow-up throw, and what the player’s point is (remember that the point is the value of the previous throw). In our implementation, these values will be held by so-called global variables, variables defined with var statements outside of any function definition so as to retain their value (the values of variables declared inside of functions disappear when the function stops executing). You don’t always need to use variables. For example, the first application we create here sets up variables to hold the horizontal and vertical position of the dice. I could have put literal numbers in the code because I don’t change these numbers, but since I refer to these values in several different places, storing the values in variables mean that if I want to change one or both, I only need to make the change in one place. Programmer-Defined Functions JavaScript has many built-in functions and methods, but it doesn’t have everything you might need. For example, as far as I know, it does not have functions specifically for simulating the throwing of dice. So JavaScript lets us define and use our own functions. These functions can take arguments, like the Math.floor method, in which the argument, say the variable rawScore in the invocation Math.floor(rawScore), is used to calculate to biggest whole number not bigger than the current value of rawScore. The statement score = Math.floor(rawScore); would be used to set the variable score with whole numbers, based on values in rawScore, which may have fractional parts. I am showing off a use of camel casing. Do keep in mind that it is my coding and only my coding that makes the connection. 34 Chapter 2 Dice Game Arguments are values that may be passed to the function. Think of them as extra information. The format for a function definition is the term function followed by the name you want to give the function, followed by parentheses holding the names of any arguments, followed by an open bracket, some code, and then a closed bracket. As I note in the previous sections, the programmer chooses the name. Here’s an example of a function definition that returns the product of the two arguments. As the name indicates, you could use it to compute the area of a rectangle. function areaOfRectangle(wd,ln) { return wd * ln; } Notice the return keyword. This tells JavaScript to send the result of the function back to us. In our example, this lets us write something like rect1 = areaOfRectangle(5,10), which would assign a value of 50 (5 × 10) to our rect1 variable. The function definition would be written as code within the script element. It might or might not make sense to define this function in real life because it is pretty easy to write multiplication in the code, but it does serve as a useful example of a programmer- defined function. Once this definition is executed, which probably would be when the HTML file is loaded, other code can use the function just by calling its name, as in areaOfRectangle(100,200) or areaOfRectangle(x2-x1,y2-y1). The second expression assumes that x1, x2, y1, y2 refer to coordinate values that are defined elsewhere. Functions also can be called by setting certain tag attributes. For example, the body tag can include a setting for the onLoad attribute: <body onLoad="init();"> My JavaScript code contains the definition of a function I call init. Putting this into the body element means that JavaScript will invoke my init function when the browser first loads the HTML document or whenever the player clicks on the reload/refresh button. Similarly, using one of the new features of HTML5, I could include the button element: <button onClick="throwdice();">Throw dice </button> 35 Chapter 2 Dice Game This creates a button holding the text Throw dice. When the player clicks it, JavaScript invokes the throwdice function I defined in the script element. The form element, described later, could invoke a function in a similar way. Conditional Statements: if and switch The craps game has a set of rules. One way to summarize the rules is to say, if it is a first-throw situation, we check for certain values of the dice throw. If it’s not the first throw, we check for other values of the dice throw. JavaScript provides the if and switch statements for such purposes. The if statement is based on conditions, which can be a comparison or a check for equality—for example, is a variable named temp greater than 85 or does the variable named course hold the value "Programming Games". Comparisons produce two possible logical values—true or false. So far you’ve seen values that are numbers and values that are strings of characters. Logical values are yet another datatype. They are also called Boolean values, after the mathematician, George Boole. The condition and check that I mentioned would be written in code as temp>85 and course == "Programming Games" Read the first expression as: Is the current value of the variable temp greater than 85? And the second one as: Is the current value of the variable course the same as the string "Programming Games"? The comparison example is easy to understand; we use > to check if one value is greater than another and < to check the opposite. The value of the expression will be one of the two logical values, true or false. The second expression is probably a little more confusing. You may be wondering about the two equals signs and maybe also the quotation marks. The comparison operator in JavaScript (and several other programming languages) that checks for equality is this combination of two equals signs. We need two equals signs because the single equals sign is used in assignment statements and it can’t do double duty. If we had written course = "Programming Games", we would have been assigning the value "Programming Games" to our course variable rather than comparing the two items. The quotation marks define a string of characters, starting with P, including the space, and ending with s. 36 Chapter 2 Dice Game With that under our belts, we can now look at how to write code that does something only if a condition is true. if (condition) { code } If we want our code to do one thing if a condition is true and another thing if it is NOT true, the format is: if (condition) { if true code } else { if not true code } Note that I used italics here because this is what is called pseudo-code, not real JavaScript that we would include in our HTML document. Here are some real code examples. They use alert, a built-in function that causes a small window with the message indicated by the argument given between the parentheses to pop up in the browser. The user must click OK to continue. if (temp>85) { alert("It is hot!"); } if (age >= 21) { alert("You are old enough to buy a drink."); } else { alert("You are too young to be served in a bar."); } We could write the craps application using just if statements. However, JavaScript supplies another construct that makes things easier to understand—the switch statement. The general format is: switch(x) { case a: codea; 37 Chapter 2 Dice Game case b: codeb; default: codec; } JavaScript evaluates the value of x in the first line of the switch statement and compares it to the values indicated in the cases. Once there is a hit, that is, x is determined to be equal to a or b, the code following the case label is executed. If there is no match, the code after default is executed. It’s not necessary to have a default possibility. Left to its own devices, the computer would continue running through the switch statement even if it found a matching case statement. If you want it to stop when you find a match, you need to include a break statement to break out of the switch. You can probably see already how if and switch will do what we need for the dice game. You’ll read how in the next section. First, let’s look at an example that determines the number of days in the month indicated by the variable mon holding three-letter abbreviations ("Jan", "Feb", etc.). switch(mon) { case "Sep": case "Apr": case "Jun": case "Nov": alert("This month has 30 days."); break; case "Feb": alert("This month has 28 or 29 days."); break; default: alert("This month has 31 days."); } If the value of the variable mon is equal to "Sep", "Apr", "Jun", or "Nov", control flows to the first alert statement and then exits the switch statement because of the break. If the value of the variable mon is equal to "Feb", the alert statement mentioning 28 or 29 days executes and then the control flow exits the switch. If the value of mon is anything else, including, by the way, an invalid three-letter abbreviation, the alert mentioning 31 days is executed. 38 Chapter 2 Dice Game Just as HTML ignores line breaks and other whitespace, JavaScript does not require a specific layout for these statements. You could put everything on one line if you wanted to. However, make things easy on yourself and use multiple lines and indenting. D rawing on the Canvas Now we get to one of the most powerful new features in HTML5, the canvas element. I will explain the pieces of coding that go into an application involving canvas, then show some simple examples, and finally get back to our goal of drawing dice faces on the canvas. Recall that the outline for an HTML document is <html> <head> <title>... </title> <style>...</style> <script> .... </script> </head> <body> ... Here is where the initial static content will go... </body> </html> Note: You do not have to include a title or a style or a script element and they can be in any order. The favorites example in Chapter 1 made use a style element, but the dice example will not. To work with the canvas, we include the tags for canvas in the body element of the HTML document and JavaScript in the script element. I’ll start by describing a standard way to write a canvas element. <canvas id="canvas" width="400" height="300"> Your browser doesn't support the HTML5 element canvas. </canvas> If an HTML file with this coding is opened by a browser that does not recognize canvas, the message Your browser doesn't support the HTML5 element canvas. appears on the screen. If you were preparing web pages for all common browsers, you could choose to direct visitors to your site to something else or try another strategy. In this book, I just focus on HTML5. 39 Chapter 2 Dice Game The HTML canvas tag defines this element to have an id of “canvas”. This could have been anything, but there’s no harm in using canvas. You can have more than one canvas, however, and in that case, you would need to use distinct values for each ID. That’s not what we do for this application, though, so we don’t have to worry about it. The attributes of width and height are set to specify the dimensions of this canvas element. Now that we’ve seen the canvas in the body, let’s look at the JavaScript. The first step in drawing on the canvas is to define the appropriate object in the JavaScript code. To do this, I need a variable so I set up one named ctx with the line var ctx; outside of any function definition. This makes it a global variable that can be accessed or set from any function. The ctx variable is something that’s needed for all drawing. I chose to name my variable ctx, short for context, copying many of the examples I’ve seen online. I could have chosen any name. Later in the code (you’ll see all the code in the examples that follow, and you can download the source code), I write the code to set the value of ctx. ctx = document.getElementById('canvas').getContext('2d'); The statement setting ctx is in a function I define named init that is referenced in the body tag <body onload=”init();> Placing the statement in the init function means that the statement is invoked AFTER everything in the body is downloaded and BEFORE any other function is invoked. What the assignment statement setting ctx does is first get the element in the document with the ID 'canvas' and then extract what is called the '2d' context. We can all anticipate that the future may bring other contexts! For now, we use the 2d one. In the JavaScript coding, you can draw rectangles, paths including line segments and arcs, and position image files on the canvas. You can also fill in the rectangles and the paths. Before we do this, however, we need to tackle coordinate systems and radian measures. Just as a global positioning system uses latitude and longitude to define your location on the map, we need a way to specify points on the screen. These points are called pixels, and we used them in the previous chapter to specify the width of images and the thickness of borders. The pixel is a pretty small unit of measurement, as you 40 Chapter 2 Dice Game can see if you do any experiments. However, it’s not enough for everyone to agree on the linear unit. We also need to agree on the point from which we are measuring, just as GPS systems use the Greenwich Meridian and the equator. For the two-dimensional rectangle that is the canvas, this goes by the name origin or registration point. The origin is the upper-left corner of the canvas element. Note that in Chapter 6, when we describe the quiz show by creating and positioning elements in the HTML document and not in a canvas element, the coordinate system is similar. The origin is still the upper-left corner of the window. This is different from what you may recall from analytical geometry or from making graphs. The horizontal numbers increase in value moving from left to right. The vertical numbers increase in value moving down the screen. The standard way to write coordinates is to put the horizontal value first, followed by the vertical value. In some situations, the horizontal value is referred to as the x value and the vertical, the y value. In other situations, the horizontal value is the left (think of it as from the left) and the vertical value is the top (think of it as from the top). Figure 2-5 shows the layout of a browser window 900 pixels wide by 600 high. The numbers indicate the coordinate values of the corners and the middle. Figure 2-5. Coordinate system for browser window Now we’ll look at several statements for drawing, and then put them together to draw simple shapes (see Figures 2-6 through 2-10). After that we’ll see how to draw the dots and rectangles to represent die faces. 41 Chapter 2 Dice Game Here’s the HTML5 JavaScript code for drawing a rectangle: ctx.strokeRect(100,50,200,300); This draws a hollow rectangle, with its top-left corner 100 pixels from the left side and 50 pixels down from the top. The rectangle has width 200 and height 300. This statement would use whatever the current settings are for line width and for color. The next piece of code demonstrates setting the line width to 5 and the color of the stroke, that is, the outline to the indicated RGB value, namely red. The rectangle is drawn using the values in the variables x, y, w, and h. ctx.lineWidth = 5; ctx.strokeStyle = "rgb(255,0,0)"; ctx.strokeRect(x,y,w,h); This snippet ctx.fillStyle = "rgb(0,0,255)"; ctx.fillRect(x,y,w,h); draws a solid blue rectangle at the indicated position and dimensions. If you want to draw a blue rectangle with a red outline, you use two lines of code: ctx.fillRect(x,y,w,h); ctx.strokeRect(x,y,w,h); HTML5 lets you draw so-called paths consisting of arcs and line segments. Line segments are drawn using a combination of ctx.moveTo and ctx.lineTo. I’ll cover them in a number of chapters: for the slingshot game in Chapter 4, the memory game using polygons in Chapter 5, and Hangman in Chapter 9. In the cannon ball game in Chapter 4, I’ll also show you how to tilt a rectangle, and the Hangman game in Chapter 9 demonstrates how to draw ovals. In this chapter, I’ll focus on the arcs. You start a path using ctx.beginPath(); and end it, with the path being drawn, with either ctx.closePath(); ctx.stroke(); 42 Chapter 2 Dice Game or ctx.closePath(); ctx.fill(); There also are situations when you can omit the call to closePath. An arc can be a whole circle or part of a circle. In the dice applications, we draw only whole circles to represent the pips on the face of each die, but I’ll explain how arcs work in general to make the code less mysterious. The method for drawing arcs has the following format: ctx.arc(cx, cy, radius, start_angle, end_angle, direction); where cx, cy, and radius are the center horizontal and vertical coordinates and the radius of the circle. To explain the next two parameters requires discussing ways to measure angles. You’re familiar with the degree unit for angles: we speak of making a 180-degree turn, meaning a U-turn, and a 90-degree angle is produced by two perpendicular lines. But most computer programming languages use another system, called radians. Here’s one way to visualize radians—think of taking the radius of a circle and laying it on the circle itself. You can dig into your memory and realize that it won’t be a neat fit, because there are 2* PI radians around the circle, somewhat more than 6. So if we want to draw an arc that is a whole circle, we specify a starting angle of 0 and an end angle of 2*PI. Luckily, the Math class furnishes a constant Math.PI that is the value of PI (to as much accuracy, as many decimal places, as necessary), so in the code, we write 2*Math.PI. If we want to specify an arc that is half a circle, we use Math.PI, while a right angle (90 degrees) will be .5*Math.PI. The arc method requires one more argument, direction. How are we drawing these arcs? Think of the movement of the hands on a clock face. In HTML 5, clockwise is the false direction and counterclockwise is the true direction. (Don’t ask why. That’s just the way it’s specified in HTML5.) I use the built-in JavaScript values true and false. This will be important when we need to draw arcs that are not whole circles. The nature of the particular problem dictates how you define the angles if you need to draw arcs that are not full circles. Here are some examples, with the complete code, for you to create (using TextPad or TextWrangler) and then vary to test your understanding. The first one draws an arc, representing a smile. 43 Chapter 2 Dice Game <html> <head> <title>Smile</title> <script> function init() { var ctx =document.getElementById("canvas").getContext('2d'); ctx.beginPath(); ctx.strokeStyle = "rgb(200,0,0)"; ctx.arc(200, 200,50,0,Math.PI, false); ctx.stroke(); } </script> </head> <body onLoad="init();"> <canvas id="canvas" width="400" height="300"> Your browser doesn't support the HTML5 element canvas. </canvas> </body> </html> Figure 2-6 shows a portion of the screen with the arc produced by this code. Figure 2-6. The “smile” produced by the expression ctx.arc(200,200,50,0, Math.PI, false); You can look ahead to Figures 2-11, 2-12, and 2-13, in which I captured more of the screen to see the positioning of the drawing. Please vary the numbers in your own example so you can gain an understanding of how the coordinate system works and how big a pixel actually is. 44 Chapter 2 Dice Game Before going on to see a frown, try making the arc wider or taller or changing the color. Then try moving the whole arc up, down, left, and right. Hint: you need to change the line ctx.arc(200, 200,50,0,Math.PI, false); Change the 200,200 to reset the center of the circle and the 50 to change the radius. Now, let’s go on with other variations. Do take each one and experiment with it. Changing the last parameter of the arc method to true: ctx.arc(200,200,50,0,Math.PI,true); makes the arc go in a counterclockwise direction. The complete code is: <html> <head> <title>Frown</title> <script type="text/javascript"> function init() { var ctx =document.getElementById("canvas").getContext('2d'); ctx.beginPath(); ctx.strokeStyle = "rgb(200,0,0)"; ctx.arc(200, 200,50,0,Math.PI, true); ctx.stroke(); } </script> </head> <body onLoad="init();"> <canvas id="canvas" width="400" height="300"> Your browser doesn't support the HTML5 element canvas. </canvas> </body> </html> Notice that I also changed the title. The title appears on a tab in the browser. Your users/audience do notice the titles. I find that I use titles in debugging to keep track of different versions. This code produces the screen shown in Figure 2-7. 45 Chapter 2 Dice Game Figure 2-7. The “frown” produced by the expression ctx.arc(200,200,50,0,Math.PI, true); Putting in the statement to close the path before the stroke: ctx.closePath(); ctx.stroke(); in the frown example, will “finish off” the arc. The complete code is <html> <head> <title>Frown</title> <script type="text/javascript"> function init() { var ctx =document.getElementById("canvas").getContext('2d'); ctx.beginPath(); ctx.strokeStyle = "rgb(200,0,0)"; ctx.arc(200, 200,50,0,Math.PI, true); ctx.closePath(); ctx.stroke(); } </script> </head> <body> <body onLoad="init();"> <canvas id="canvas" width="400" height="300"> Your browser doesn't support the HTML5 element canvas. </canvas> </body> </html> 46 Chapter 2 Dice Game This produces the screen shown in Figure 2-8. Figure 2-8. The frown becomes a half-circle by adding ctx.closePath(); before ctx.stroke(); The closePath command is not always necessary, but it’s good practice to include it. You will notice that I wait to invoke closePath and fill the statements for the multiple dots. Experiment here and also look ahead to the drawing of the slingshot in Chapter 5 and the drawing of the hangman figure in Chapter 9. If you want the path filled in, you use ctx.fill() in place of ctx.stroke(), which produces a black, filled-in shape, as shown in Figure 2-9. The complete code is <html> <head> <title>Smile</title> <script type="text/javascript"> function init() { var ctx =document.getElementById("canvas").getContext('2d'); ctx.beginPath(); ctx.strokeStyle = "rgb(200,0,0)"; ctx.arc(200, 200,50,0,Math.PI, false); ctx.closePath(); ctx.fill(); } </script> </head> <body onLoad="init();"> <canvas id="canvas" width="400" height="300"> 47 Chapter 2 Dice Game Your browser doesn't support the HTML5 element canvas. </canvas> </body> </html> Black is the default color. Figure 2-9. Filling in the half circle using ctx.fill() If you want a shape to be filled and have a distinct outline, you use both the fill and the stroke commands and specify different colors using the fillStyle and strokeStyle properties. The color scheme is based on the same red/green/blue codes introduced in Chapter 1. You can experiment or use a tool such as Photoshop or the online photo editor pixlr.com to get the colors you want. Here is the complete code: <html> <head> <title>Smile</title> <script type="text/javascript"> function init() { var ctx =document.getElementById("canvas").getContext('2d'); ctx.beginPath(); ctx.strokeStyle = "rgb(200,0,0)"; ctx.arc(200, 200,50,0,Math.PI, false); ctx.fillStyle = "rgb(200,0,200)"; ctx.closePath(); ctx.fill(); ctx.strokeStyle="rgb(255,0,0)"; ctx.lineWidth=5; ctx.stroke(); } 48 Chapter 2 Dice Game </script> </head> <body onLoad="init();"> <canvas id="canvas" width="400" height="300"> Your browser doesn't support the HTML5 element canvas. </canvas> </body> </html> This code produces a half circle filled in with purple (a combination of red and blue),