Tải bản đầy đủ (.pdf) (444 trang)

HTML5 and javascript projects

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (20.88 MB, 444 trang )

HTML5 and JavaScript
Projects

■■■
Jeanine Meyer


HTML5 and JavaScript Projects
Copyright © 2011 by Jeanine Meyer
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-4302-4032-7
ISBN-13 (electronic): 978-1-4302-4033-4
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.
President and Publisher: Paul Manning
Lead Editor: Jonathan Gennick
Technical Reviewer: Andrew Zack
Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Jonathan Gennick,
Jonathan Hassell, Michelle Lowman, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Frank
Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Matt Wade, Tom Welsh
Coordinating Editor: Adam Heath
Copy Editor: Damon Larson
Production Support: Patrick Cunningham
Indexer: SPi Global


Artist: SPi Global
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
, or visit www.springeronline.com.
For information on translations, please e-mail , or visit www.apress.com.
Apress and friends of ED books 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
Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have
any liability to any person or entity with respect to any loss or damage caused or alleged to be caused
directly or indirectly by the information contained in this work.
The source code for this book is available to readers at www.apress.com. You will need to answer
questions pertaining to this book in order to successfully download the code.


To my expanding family, including Annika Lyyli and her parents and brothers;
and Esther, Aviva, and Anne, who take care of me now;
and to my father, who takes care of me still.


Contents at a Glance
About the Author ....................................................................................................... xi
About the Technical Reviewer .................................................................................. xii
Acknowledgments ................................................................................................... xiii
Introduction ............................................................................................................. xiv
■Chapter 1: Building the HTML5 Logo – Drawing on Canvas,
with Scaling, and Semantic Tags ........................................................... 1
■Chapter 2: Family Collage: Manipulating Programmer-defined Objects

on a Canvas.......................................................................................... 19
■Chapter 3: Bouncing Video: Animating and Masking HTML5 Video ....................... 53
■Chapter 4: Map Maker: Combining Google Maps and the Canvas ......................... 89
■Chapter 5: Map Portal: Using Google Maps to Access Your Media ..................... 129
■Chapter 6: Where am I: Using Geolocation, the Google Maps API, and PHP ........ 183
■Chapter 7: Origami Directions: Using Math-Based Line Drawings,
Photographs, and Videos ................................................................... 225
■Chapter 8: Jigsaw Video: Using the Mouse and Touch to Arrange Images ......... 283
■Chapter 9: US States Game: Building a Multiactivity Game ................................. 321
■Chapter 10: Web Site Database: Using PHP and MySQL ...................................... 367
Index ....................................................................................................................... 425

iv


Contents
About the Author ....................................................................................................... xi
About the Technical Reviewer .................................................................................. xii
Acknowledgments ................................................................................................... xiii
Introduction ............................................................................................................. xiv
■Chapter 1: Building the HTML5 Logo – Drawing on Canvas, with Scaling,
and Semantic Tags................................................................................. 1
Introduction ....................................................................................................................... 1
Project History and Critical Requirements ......................................................................... 4
HTML5, CSS, and JavaScript features ............................................................................... 5
Drawing paths on canvas ......................................................................................................................... 5
Placing text on canvas and in the body of a document ............................................................................ 7
Coordinate transformations ...................................................................................................................... 8
Using the range input element ................................................................................................................. 9


Building the application and making it your own ............................................................ 11
Testing and uploading the application............................................................................. 18
Summary ......................................................................................................................... 18
■Chapter 2: Family Collage: Manipulating Programmer-defined Objects
on a Canvas.......................................................................................... 19
Introduction ..................................................................................................................... 19
Critical Requirements ...................................................................................................... 21

v


■ CONTENTS

HTML5, CSS, and JavaScript features ............................................................................. 22
JavaScript objects .................................................................................................................................. 22
User interface ......................................................................................................................................... 31
Saving the canvas to an image .............................................................................................................. 34

Building the application and making it your own ............................................................ 35
Testing and uploading the application............................................................................. 52
Summary ......................................................................................................................... 52
■Chapter 3: Bouncing Video: Animating and Masking HTML5 Video ....................... 53
Introduction ..................................................................................................................... 53
Project History and Critical Requirements ....................................................................... 58
HTML5, CSS, and JavaScript Features ............................................................................ 59
Definition of the Body and the Window Dimensions............................................................................... 59
Animation ............................................................................................................................................... 61
Video Drawn on Canvas and As a Movable Element .............................................................................. 64
Traveling Mask ....................................................................................................................................... 66
User Interface ......................................................................................................................................... 68


Building the Application and Making It Your Own ........................................................... 68
Making the Application Your Own .......................................................................................................... 85

Testing and Uploading the Application ............................................................................ 86
Summary ......................................................................................................................... 87
■Chapter 4: Map Maker: Combining Google Maps and the Canvas ......................... 89
Introduction ..................................................................................................................... 89
Latitude & Longitude and Other Critical Requirements ................................................... 98
HTML5, CSS, and JavaScript Features .......................................................................... 104
Google Maps API ................................................................................................................................... 104
Canvas Graphics ................................................................................................................................... 105
Cursor ................................................................................................................................................... 109

vi


■ CONTENTS

Events ................................................................................................................................................... 109
Calculating Distance and Rounding Values for Display ........................................................................ 113

Building the Application and Making It Your Own ......................................................... 114
Testing and Uploading the Application .......................................................................... 127
Summary ....................................................................................................................... 127
■Chapter 5: Map Portal: Using Google Maps to Access Your Media ..................... 129
Introduction ................................................................................................................... 129
Project History and Critical Requirements ..................................................................... 137
HTML5, CSS, and JavaScript Features .......................................................................... 137
Google Maps API for Map Access and Event Handling ......................................................................... 138

Project Content ..................................................................................................................................... 141
Presentation and Removal of Video, Audio and Images ....................................................................... 142
Distances and Tolerances .................................................................................................................... 144
Regular Expressions ............................................................................................................................. 145
External Script File ............................................................................................................................... 146
Dynamic Creation of HTML5 Markup and Positioning .......................................................................... 147
Hint Button............................................................................................................................................ 149
Shuffling ............................................................................................................................................... 149

Building the Application and Making It Your Own ......................................................... 150
The Mapvideos Application................................................................................................................... 150
The Mapmediabase Application ........................................................................................................... 160
The Quiz Application ............................................................................................................................. 170

Testing and Uploading the Application .......................................................................... 182
Summary ....................................................................................................................... 182
■Chapter 6: Where am I: Using Geolocation, the Google Maps API, and PHP ........ 183
Introduction ................................................................................................................... 183
Geolocation and Other Critical Requirements ................................................................ 194

vii


■ CONTENTS

HTML5, CSS, JavaScript, and PHP Features .................................................................. 196
Geolocation ........................................................................................................................................... 196
Reverse Geocoding ............................................................................................................................... 200
Clicking the Map ................................................................................................................................... 202
Checking E-mail Address Input and Invoking PHP to send e-mail ....................................................... 203

A Brief Introduction to the PHP Language ............................................................................................ 204

Building the Application and Making It Your Own ......................................................... 205
Testing and Uploading the Application .......................................................................... 223
Summary ....................................................................................................................... 224
■Chapter 7: Origami Directions: Using Math-Based Line Drawings,
Photographs, and Videos ................................................................... 225
Introduction ................................................................................................................... 225
Critical Requirements .................................................................................................... 232
HTML5, CSS, JavaScript Features, and Mathematics.................................................... 233
Overall Mechanism for Steps ............................................................................................................... 233
User Interface ....................................................................................................................................... 235
Coordinate Values ................................................................................................................................. 236
Utility Functions for Display .................................................................................................................. 237
Utility Functions for Calculation ............................................................................................................ 239
Step Line Drawing Functions ................................................................................................................ 240
Displaying a Photograph....................................................................................................................... 247
Presenting and Removing a Video ........................................................................................................ 247

Building the Application and Making It Your Own ......................................................... 248
Testing and Uploading the Application .......................................................................... 282
Summary ....................................................................................................................... 282
■Chapter 8: Jigsaw Video: Using the Mouse and Touch to Arrange Images ......... 283
Introduction ................................................................................................................... 283
Background and Critical Requirements ......................................................................... 293

viii


■ CONTENTS


HTML5, CSS, JavaScript, and Programming Features ................................................... 294
Acquiring the Images and Data for the Pieces ..................................................................................... 294
Dynamically Created Elements ............................................................................................................. 295
Setting Up the Jigsaw Puzzle ............................................................................................................... 297
Handling Mouse and Finger Touch Events ........................................................................................... 297
Calculating If the Puzzle Is Complete ................................................................................................... 303
Preparing, Positioning, and Playing the Video and Making It Hidden or Visible ................................... 305

Building the Application and Making It Your Own ......................................................... 305
Testing and Uploading the Application .......................................................................... 319
Summary ....................................................................................................................... 319
■Chapter 9: US States Game: Building a Multiactivity Game ................................. 321
Introduction ................................................................................................................... 321
Critical Requirements .................................................................................................... 329
HTML5, CSS, JavaScript Features, Programming Techniques, and Image Processing . 329
Acquiring the Image Files for the Pieces and Determining Offsets ...................................................... 329
Creating Elements Dynamically ............................................................................................................ 335
User Interface Overall ........................................................................................................................... 336
User Interface for Asking the Player to Click a State ............................................................................ 336
User Interface for Asking the Player to Name a State .......................................................................... 337
Spreading Out the Pieces ..................................................................................................................... 338
Setting Up the Jigsaw Puzzle ............................................................................................................... 339
Saving and Recreating the State of the Jigsaw Game and Restoring the Original Map ....................... 340

Building the Application and Making It Your Own ......................................................... 343
Testing and Uploading the Application .......................................................................... 364
Summary ....................................................................................................................... 364

ix



■ CONTENTS

■Chapter 10: Web Site Database: Using PHP and MySQL ...................................... 367
Introduction ................................................................................................................... 367
Critical Requirements .................................................................................................... 376
SQL, PHP, HTML5, and JavaScript Features .................................................................. 377
Relational Databases ............................................................................................................................ 377
SQL ....................................................................................................................................................... 379
Local Storage........................................................................................................................................ 381
Hash Function ....................................................................................................................................... 382
Client Side vs. Server Side for Input Validation .................................................................................... 382
Middleware: PHP .................................................................................................................................. 383

Building the Application and Making It Your Own ......................................................... 390
Testing and Uploading the Application .......................................................................... 422
Summary ....................................................................................................................... 423
Index ....................................................................................................................... 425

x


About the Author
■Jeanine Meyer is a full professor at Purchase College/State University of New
York. She teaches courses for students majoring in mathematics/computer
science and new media. She developed and teaches a course on understanding
quantitative information for humanities students. The web site for her academic
activities is Before coming to
academia, she was a research staff member and manager at IBM Research,

focusing on robotics and manufacturing research, and she later worked as a
research consultant at IBM for educational grant programs.
After having a great time in 2010 developing The Essential Guide to HTML5:
Using Games to Learn HTML5 and JavaScript, Jeanine looked forward to a
similar experience doing this book, and her expectations were met. She also
needed to be occupied while awaiting the birth of her granddaughter (see
Chapter 2). Family members also are documented in Chapters 3, 5, and 8. She
continues to enjoy doing crossword puzzles and ken ken, knitting and
crocheting, reading novels and history, gardening, eating Aviva’s extraordinary cooking, listening to her
mother on piano, and playing the flute. She still and again is an active volunteer and letter-to-the-editor
writer for progressive causes and candidates.

xi


About the Technical Reviewer
■Andrew Zack is the CEO of ZTMC (), specializing in search engine optimization (SEO)
and Internet marketing strategies. His project background includes almost 20 years of site development
and project management experience and over 15 years as an SEO and Internet marketing expert.
Andrew has also been very active in the publishing industry, having coauthored Flash 5 Studio
(Apress, 2001) and served as a technical reviewer on over ten books and industry publications.

xii


Acknowledgments
Much appreciation to my students and colleagues at Purchase College/State University of New York. In
particular, for Chapter 5, which covers the map portal, I want to thank Jennifer Douglas, Jeremy
Martinez, and Nik Dedvukaj for the maze video clip produced in my Robotics class in 2008, and my
mother for her piano playing recorded as an audio clip. Thanks also to the LA HTML5 MeetUp group,

especially Samy Kamkar, Matthew Sacks, and Tiffany Brown for their help and also their requests for
help, which gave me ideas. Thanks to Daniel Davis for his HTML5 logo; Mike Taylor for video advice;
David Keefe, who always is an inspiration; Aviva Meyer, Anne Kellerman, John McMullen, and Barbara
McMullen for their testing help on iPhones and iPads; and Palmer Agnew and Daniel Meyer for general
support and helping me better understand geolocation.
Thanks to the crew at Apress/friends of Ed: Ben Renow-Clarke, Adam Heath, Andrew Zack, Damon
Larson, Nancy Wright, Michael Spano and others who made this book much better than I could have on
my own.

xiii


Introduction
This book continues my exploration of HTML5. My approach in developing the projects was to combine
features such as canvas and video; attempt more intricate drawing, making use of mathematics; and
make use of standard programming techniques such as object-oriented programming and separation of
content and logic. I was also interested in building applications combining HTML5 and JavaScript with
other technologies, including Google Maps, geolocation, and server-side programming.
Each chapter in the book is focused on an application or set of related applications. This is because
my experience as a teacher and a learner has shown that concepts and mechanics are best understood in
the context of actual use. The applications start off with drawing the HTML5 official logo. As you will find
out in Chapter 1, the way I developed this application prompted a use of coordinate transformations.
The project in Chapter 2, involving a family collage, was inspired by my growing family and the desire to
teach about object-oriented programming. It is a good application for you to use as a foundation to
create your own, with your own photos and objects of your own invention. Chapter 3, which shows how
to create a bouncing video, was built on other two-dimensional applications I have created, and features
two different ways to combine canvas and video.
Chapters 4, 5, and 6 demonstrate use of the Google Maps API (Application Programming Interface),
a powerful facility that allows you to incorporate access to Google Maps as part of your own projects.
Chapter 4 presents a user interface combining a map and canvas, and includes a custom-designed

cursor and the use of alpha (transparency) in drawing paths. The three applications discussed in
Chapter 5 all demonstrate the use of mapping as a portal to media. The sequence of applications shows
you how to separate content and logic so you can scale up to various applications (e.g., a tour of a region
or a geography quiz with many locations). Chapter 6 features geolocation, technology to determine the
location of your end-user. I combine this with server-side programming using PHP that allows you to
send an e-mail of where you are to someone the end-user chooses.
In Chapter 7, I use the production of directions for origami to show how to combine line drawings,
often using mathematical expressions, and video and photographs. You can use this as a model for your
own set of directions using drawings, video, and images, or let the reading refresh your memory for
topics in algebra and geometry. Chapter 8 was inspired by a project I produced using Adobe Flash, in
which a jigsaw puzzle is transformed into a video. In the project in this chapter, you’ll also learn how to
make this work on an iPod and iPad, including how to incorporate the handling of finger touch events.
Similarly, Chapter 9 was initially inspired by an identify-and-name-the-state game I made using Flash.
This chapter includes the challenge of mixing up the states in the form of a jigsaw puzzle, including the
feature of saving the puzzle-in-progress using localStorage. The resulting educational game presents a
user interface that must handle multiple types of player actions. Chapter 10, the last chapter,
demonstrates use of a database. In this chapter, HTML5 and JavaScript are combined with PHP and
Structured Query Language (SQL), which is the standard language for most databases. The database
featured in the chapter is MySQL. The form validation features of HTML5 along with localStorage
address common requirements of many database applications. The database application also
demonstrates one-way encryption for user passwords and the combination of client-side and serverside form validation.

xiv


■ INTRODUCTION

Who Is This Book For?
I do believe my explanations are complete, but I am not claiming, as I did for my previous book, The
Essential Guide to HTML5, that this book is for the total beginner. This book is for the developer who has

some knowledge of programming and who wants to build (more) substantial applications by combining
basic features and combining JavaScript with other technologies. It also can serve as an idea book for
someone working with programmers to get an understanding of what is possible.

How Is This Book Structured?
This book consists of ten chapters, each organized around an application or type of application. You can
skip around. However, it probably makes sense to read Chapter 4 before 5 or 6. Also, the PHP server-side
language is used in a simple way in Chapter 6 and then more fully in Chapter 10. Other cross-references
are indicated in the text. Each chapter starts with an introduction to the application, with screenshots of
the applications in use. In several cases, the differences between browsers are shown. The chapters
continue with a discussion of the critical requirements, where concepts are introduced before diving
into the technical details. The next sections describe how the requirements are satisfied, with specific
constructs in HTML5, JavaScript, PHP, and/or SQL, and with standard programming techniques. I then
show the application coding line by line with comments. Each chapter ends with instructions and tips
for testing and uploading the application to a server, and a summary of what you learned.
The code (with certain exceptions noted for Chapter 10) is all included as downloads available from
the publisher. In addition, the figures are available as full-color TIFF files. Of course, you will want to use
your own media for the projects shown in Chapters 2, 3, 5, and 8. My media (video, audio, images) is
included with the code and this includes images for the 50 states for the states game in Chapter 9. You
can use the project as a model for a different part of the world or a puzzle based on an image or diagram.
Let’s get started.

xv


CHAPTER 1

Building the HTML5 Logo –
Drawing on Canvas, with Scaling,
and Semantic Tags

In this chapter, we will review


Drawing paths on a canvas



Placing text on a canvas



Coordinate transformations



Fonts for text drawn on canvas and fonts for text in other elements



Semantic tags



The range input element

Introduction
The project for this chapter is a presentation of the official HTML5 logo, with accompanying text. The
shield and letters of the logo are drawn on a canvas element and the accompanying text demonstrates
the use of semantic tags. The viewer can change the size of the logo using a slider input device. It is an
appropriate start to this book, a collection of projects making use of HTML5, JavaScript and other

technologies, because of the subject matter and because it serves as a good review of basic event-driven
programming and other important features in HTML5. The way I developed the project, building on the
work of others, is typical of how most of us work. In particular, the circumstances provide motivation for
the use of coordinate transformations. Lastly, at the time of writing, Firefox does not fully implement the
slider input element. Unfortunately, this also is a common situation and I will discuss the implications.
The approach of this book is to explain HTML5, Cascading Style Sheets and JavaScript chapters in
the context of specific examples. The projects represent a variety of applications and, hopefully, you will
find something in each one that you will learn and adapt for your own purposes.

J. Meyer, HTML5 and JavaScript Projects
© Jeanine Meyer 2011

1


CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS

■ Note If you need an introduction to programming using HTML5 and JavaScript, you can consult my book the
Essential Guide to HTML5 or other books published by Apress or others. There also is considerable material
available online.

Figure 1-1 shows the opening screen for the logo project on the Chrome browser. (Skip ahead to
Figure 1-3 for the appearance on Firefox.)

Figure 1-1. Opening Screen for HTML5 Logo
Notice the slider feature, the accompanying text, which contains what appears to be a hyperlink,
and the text in a footer below a yellow line. The footer also includes a hyperlink. As I will explain later,
the function and the formatting of the footer and any other semantic element is totally up to me, but
providing a reference to the owners of the logo, The World Wide Web Consortium would be deemed an
appropriate use.

The viewer can use the slider to change the size of the logo. Figure 1-2 shows the application after
the slider has been adjusted to show the logo reduced to about a third in width and in height.

2


CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS

Figure 1-2. Logo scaled down
The implementation of HTML5 is not complete by any browsers and, as it turns out, Firefox treats
all slider inputs as simple text fields. This is termed 'graceful degradation' and it certainly is better than
producing nothing at all. Figure 1-3 shows the opening screen in Firefox. Notice the initial value is
displayed as 100.

Figure 1-3. Application using Firefox

3


CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS

As will be the practice in each chapter, I now explain the critical requirements of the application,
more or less independent of the fact that the implementation will be in HTML5, and then describe the
features of HTML5, JavaScript, and other technologies as needed that will be used in the
implementation. The Building section includes a table with comments for each line of code and also
guidance for building similar applications. The Testing section provides details for uploading and
testing. This section is more critical for some projects than others. Lastly, there is a Summary that
reviews the programming concepts covered and previews what is next in the book.

Project History and Critical Requirements

The critical requirements for this project are somewhat artificial and not easily stated as something
separate from HTML. For example, I wanted to draw the logo as opposed to copying an image from the
Web. My design objectives always include wanting to practice programming and prepare examples for
my students. The shape of the shield part of the logo seemed amenable to drawing on canvas and the
HTML letters could be done using the draw text feature. In addition, there are practical advantages to
drawing images instead of using image files. Separate files need to be managed, stored, and downloaded.
The image shown in Figure 1-4 is 90KB. The file holding the code for the program is only 4KB. Drawing a
logo or other graphic means that the scale and other attributes can be changed dynamically using code.

Figure 1-4. Image of logo
I looked online and found an example of just the shield done by Daniel Davis, who works for Opera.
This was great because it meant that I did not have to measure a copy of the logo image to get the
coordinates. This begs the question of how he determined the coordinates. I don't know the answer,
even though we had a pleasant exchange of emails. One possibility is to download the image and use the
grid feature of image processing programs such as Adobe Photoshop or Corel Paint Shop Pro. Another
possibility is to use (old-fashioned) transparent graph paper.
However, there was a problem with building on Daniel Davis's work. His application did not include
the HTML letters. The solution to this was to position the letters on the screen and then move down so to
speak to position the drawing of the shield using the coordinates provided in Daniel's example. The
technical term for 'moving down the screen' is performing a coordinate transformation. So the ability to
perform coordinate transformations became a critical requirement for this project.
I chose to write something about the logo and, in particular, give credit and references in the form of
hyperlinks. I made the decision to reference the official source of the logo as brief text at the bottom of

4


CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS

the document below a line. The reference to Daniel Davis was part of the writing in the body. We

exchanged notes on font choices and I will discuss that more in the next section.
In order to give the viewer something to do with the logo, I decided to present a means of changing
the size. A good device for this is a slider with the minimum and maximum values and steps all specified.
So the critical requirements for this application include drawing shapes and letters in a specific font,
coordinate transformations, formatting a document with a main section and a footer section, and
including hyperlinks.

HTML5, CSS, and JavaScript features
I assume that you, the reader, have some experience with HTML and HTML5 documents. One of the
most important new features in HTML5 is the canvas element for drawing. I describe briefly the drawing
of filled-in paths of the appropriate color and filled-in text. Next, I describe coordinate transformations,
used in this project for the two parts of the logo itself and for scaling, changing the size, of the whole
logo. Lastly, I describe the range input element. This produces the slider.

Drawing paths on canvas
Canvas is a type of element introduced in HTML5. All canvas elements have a property (aka attribute)
called the 2D context. Typically, a variable is set to this property after the document is loaded:
ctx = document.getElementById('canvas').getContext('2d');
It is important to understand that canvas is a good name: code applies color to the pixels of the
canvas, just like paint. Code written later can put a different color on the canvas. The old color does not
show through. Even though our code causes rectangles and shapes and letters to appear, these distinct
entities do not retain their identity as objects to be re-positioned.
The shield is produced by drawing six filled-in paths in succession with the accumulated results as
shown in Figure 1-5. You can refer to this picture when examining the code. Keep in mind that in the
coordinates, the first number is the distance from the left edge of the canvas and the second number is
the distance from the top edge of the canvas.

Figure 1-5. Sequence of paths for drawing logo
By the way, I chose to show you the sequence with the accumulated results. If I displayed what is
drawn, you would not see the white parts making up the left side of the five. You can see it because it is

two white filled-in paths on top of the orange.
All drawing is done using methods and properties of the ctx variable holding the 2D context
property of the canvas element. The color for any subsequent fill operation is set by assigning a color to
the fillStyle property of the canvas context.

5


CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS

ctx.fillStyle = "#E34C26";
This particular color, given in the hexadecimal format, where the first two hexadecimal (base 16)
digits represent red, the second two hexadecimal digits represent green and the last two represent blue,
is provided by the W3C website, along with the other colors, as the particular orange for the background
of the shield. It may be counterintuitive, but in this system, white is specified by the value #FFFFFF.
Think of this as all colors together make white. The absence of color is black and specified by #000000.
The pearly gray used for the right hand side of the 5 in the logo has the value #EBEBEB. This is a high
value, close to white. It is not necessary that you memorize any of these values, but it is useful to know
black and white, and that a pure red is #FF0000, a pure green is #00FF00 and a pure blue #0000FF. You
can use the eyedropper/color picker tool in drawing programs such as Adobe Photoshop, Corel Paint
Shop Pro on the on-line tool: to find out values of colors in images OR you can use
the official designation, when available, for official images.
All drawing is done using the 2 dimensional coordinate systems. Shapes are produced using the
path methods. These assume a current location, which you can think of as the position of a pen or paint
brush over the canvas. The critical methods are moving to a location and setting up a line from the
current location to the indicated location. The following set of statements draws the five sided orange
shape starting at the lower, left corner. The closePath method closes up the path by drawing a line back
to the starting point.
ctx.fillStyle = "#E34C26";
ctx.beginPath();

ctx.moveTo(39, 250);
ctx.lineTo(17, 0);
ctx.lineTo(262, 0);
ctx.lineTo(239, 250);
ctx.lineTo(139, 278);
ctx.closePath();
ctx.fill();
If you haven't done any drawing on canvas, here is the whole HTML script needed to produce the 5sided shape. The onLoad attribute in the <body> tag causes the init function to be invoked when the
document is loaded. The init function sets the ctx variable, sets the fillStyle property and then draws
the path.
<!DOCTYPE html>
<html>
<head>
<title>HTML 5 Logo</title>
<meta charset="UTF-8">
<script>
function init() {
ctx = document.getElementById('canvas').getContext('2d');
ctx.fillStyle = "#E34C26";
ctx.beginPath();
ctx.moveTo(39, 250);
ctx.lineTo(17, 0);
ctx.lineTo(262, 0);
ctx.lineTo(239, 250);
ctx.lineTo(139, 278);
ctx.closePath();
ctx.fill();
}

6



CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS

</script>
</head>
<body onLoad="init();">
<canvas id="canvas" width="600" height="400">
Your browser does not support the canvas element .
</canvas>
</body>
</html>
Do practice and experiment with drawing on the canvas if you haven’t done so before, but I will go
on. The other shapes are produced in a similar manner. By the way, if you see a line down the middle of
the shield, this is an optical illusion.

Placing text on canvas and in the body of a document
Text is drawn on the canvas using methods and attributes of the context. The text can be filled in, using
the fillText method or drawn as an outline using the strokeText method. The color is whatever the
current fillStyle property or strokeStyle property holds. Another property of the context is the font.
This property can contain the size of the text and one or more fonts. The purpose of including more than
one font is to provide options to the browser if the first font is unavailable on the computer running the
browser. For this project, I use
var fontfamily = "65px 'Gill Sans Ultra Bold', sans-serif";
and in the init function
ctx.font = fontfamily;
This directs the browser to use the Gill Sans Ultra Bold font if it is available and if not, use whatever
the default sans-serif font on the computer.
I could have put this all in one statement, but chose to make it a variable. You can decide if my
choice of font was close enough to the official W3C logo.


■ Note There are at least two other approaches to take for this example. One possibility is to NOT use text but to
draw the letters as filled-in paths. The other is to locate and acquire a font and place it on the server holding the
HTML5 document and reference it directly using @font-face.

With the font and color set, the methods for drawing text require a string and a position: x and y
coordinates. The statement in this project to draw the letters is
ctx.fillText("HTML", 31,60);
Formatting text in the rest of the HTML document, that is, outside a canvas element, requires the
same attention to fonts. In this project, I choose to make use of the semantic elements new to HTML5
and follow the practice of putting formatting in the style element. The body of my HTML script contains
two article elements and one footer elements. One article holds the input element with a comment and
the other article holds the rest of the explanation. The footer element contains the reference to W3C.
Formatting and usage of these are up to the developer/programmer. This includes making sure the

7


CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS

footer is the last thing in the document. If I placed the footer before one or both articles, it would no
longer be displayed at the foot, that is, the bottom of the document. The style directives for this project
are the following:
footer {display:block; border-top: 1px solid orange; margin: 10px;«
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif; font-weight: bold;}
article {display:block; font-family: Georgia, "Times New Roman", Times, serif; margin: 5px;}
The styles each set up all instances of these elements to be displayed as blocks. This puts a line
break before and after. The footer has a border on the top, which produces the line above the text. Both
styles specify a list of four fonts each. So the browser first sees if Trebuchet MS is available, then checks
for Arial, then for Helvetica and then, if still unsuccessful, uses the system default sans-serif font for the

footer element. Similarly, the browser checks for Georgia, then Times New roman, then Times and then,
if unsuccessful, uses the standard serif font. This probably is overkill, but it is the secure way to operate.
The footer text is displayed in bold and the articles each have a margin around them of 5 pixels.
Formatting, including fonts, is important. HTML5 provides many features for formatting and for
separating formatting from structure and content. You do need to treat the text on the canvas differently
than the text in the other elements.

Coordinate transformations
I have given my motivation for using coordinate transformations, specifically to keep using a set of
coordinates. To review, a coordinate system is the way to specify positions on the canvas. Positions are
specified as distances from an origin point. For the two-dimensional canvas, two coordinates are
necessary: the first coordinate, governing the horizontal, often called the x and the second coordinate,
governing the vertical, called the y. A pesky fact is that when drawing to screens the y axis is flipped so
the vertical is measured from the top of the canvas. The horizontal is measured from the left. This means
that the point (100,200) is further down the screen than the point (100,100).
In the logo project, I wrote code to display the letters HTML and then move the origin to draw the
rest of the logo. An analogy would be that I know the location of my house from the center of my town
and so I can give directions to the center of town and then give directions to my house. The situation in
which I draw the letters in the logo and 'move down the screen' requires the translate transformation.
The translation is done just in the vertical. The amount of the translation is stored in a variable I named
offsety:
var offsety = 80;

ctx.fillText("HTML", 31, 60);
ctx.translate(0, offsety);
Since I decided to provide a way for the viewer to change the size of the logo, I made use of the scale
transformation. Continuing the analogy of directions, this is equivalent to changing the units. You may
give some directions in miles (or kilometers) and other directions in yards or feet or meters or, maybe,
blocks. The scaling can be done separately for each dimension. In this application, there is a variable
called factorvalue that is set by the function invoked when the input is changed. The statement

ctx.scale(factorvalue, factorvalue);
changes the units for both the horizontal and vertical direction.

8


CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS

HTML5 provides a way to save the current state of the coordinate system and restore what you have
saved. This is important if you need your code to get back to a previous state. The saving and restoring is
done using what is termed a stack: last in first out. Restoring the coordinate state is termed popping the
stack and saving the coordinate state is pushing something onto the stack. My logo project does not use
this in its full power, but it is something to remember to investigate if you are doing more complex
applications. In the logo project, my code saves the original state when the document is first loaded.
Then before drawing the logo, it restores what was saved and then saves it again so it is available the next
time. The code at the start of the function dologo, which draws the logo, starts off as follows:
function dologo() {
var offsety = 80 ;
ctx.restore();
ctx.save();
ctx.clearRect(0,0,600,400);
ctx.scale(factorvalue,factorvalue);
ctx.fillText("HTML", 31,60);
ctx.translate(0,offsety);
// 5 sided orange background
ctx.fillStyle = "#E34C26";
ctx.beginPath();
ctx.moveTo(39, 250);
ctx.lineTo(17, 0);
ctx.lineTo(262, 0);

ctx.lineTo(239, 250);
ctx.lineTo(139, 278);
ctx.closePath();
ctx.fill();
// right hand, lighter orange part of the background
ctx.fillStyle = "#F06529";
ctx.beginPath();
ctx.moveTo(139, 257);
ctx.lineTo(220, 234);
ctx.lineTo(239, 20);
ctx.lineTo(139, 20);
ctx.closePath();
ctx.fill();

Note that the canvas is cleared (erased) of anything that was previously drawn.

Using the range input element
The input device, which I call a slider, is the new HTML5 input type range, and is placed in the body of
the HTML document. Mine is placed inside an article element. The attributes of this type and other
input elements provide ways of specifying the initial value, the minimum and maximum values, the
smallest increment adjustment and the action to take if the viewer changes the slider. The code is
onChange="changescale(this.value)" step="10"/>

9


CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS

The min, max, (initial) value, and the step can be set to whatever you like. Since I was using

percentage and since I did not want the logo to get bigger than the initial value or deal with negative
values, I used 0 and 100.
In the proper implementation of the slider, the viewer does not see the initial value or the maximum
or minimum. My code uses the input as a percentage. The expression this.value is interpreted as the
value attribute of THIS element, emphasis given in capitals to convey the switch to English! The term
this has special meaning in JavaScript and several other programming languages. The changescale
function takes the value, specified by the parameter given in the assignment to the onChange attribute,
and uses it to set a global variable (a variable declared outside of any function so it persists and is
available to any function).
function changescale(val) {
factorvalue = val / 100;
dologo();
}
It is part of the specification of HTML5 that the browsers will provide form validation, that is, check
that the conditions specified by attributes in the input elements are obeyed. This can be a significant
productivity boost in terms of reducing the work programmers need to do and a performance boost
since the checking probably would be faster when done by the browser. We will discuss it more in
Chapter 10 on databases and php. In the HTML5 logo project, an advantage of the slider is that the
viewer does not need to be concerned with values but merely moves the device. There is no way to input
an illegal value. I do not want to disparage the Firefox browser, and, as I indicated, producing a text box
is better than producing nothing, but, at least at the time of writing, it does not display a slider or do any
checking. Figure 1-6 shows the results of entering a value of 200 in the input field.

Figure 1-6. Display in Firefox of scale of 200

10


Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×