Docsity
Docsity

Prepare-se para as provas
Prepare-se para as provas

Estude fácil! Tem muito documento disponível na Docsity


Ganhe pontos para baixar
Ganhe pontos para baixar

Ganhe pontos ajudando outros esrudantes ou compre um plano Premium


Guias e Dicas
Guias e Dicas


HTML5 and JavaScript Projects Apress, Manuais, Projetos, Pesquisas de Informática

Livro que ensina utilização de HTML5, Javascript e API, incluindo API do Google MAPs.

Tipologia: Manuais, Projetos, Pesquisas

2011

Compartilhado em 10/11/2011

samuel-ritter-4
samuel-ritter-4 🇧🇷

3 documentos

1 / 446

Toggle sidebar

Esta página não é visível na pré-visualização

Não perca as partes importantes!

bg1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Pré-visualização parcial do texto

Baixe HTML5 and JavaScript Projects Apress e outras Manuais, Projetos, Pesquisas em PDF para Informática, somente na Docsity!

For your convenience Apress has placed some of the front

matter material after the index. Please use the Bookmarks

and Contents at a Glance links to access them.

xiv

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 server- side form validation.

■ INTRODUCTION

xv

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.

■ 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.

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

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.

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: http://pixlr.com/ 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 5- sided shape. The onLoad attribute in the **** 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.

**

HTML 5 Logo

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.

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


The canvas is of fixed width and height and drawing outside the canvas, which is what is done when the scaling is done to accept numbers and stretch them out to twice the original value, is ignored.

Building the application and making it your own

The project does one thing, draw the logo. A function, dologo , is defined for this purpose. Informally, the outline of the program is

  1. init: initialization
  2. dologo: draw the logo starting with the HTML letters and then the shield
  3. changescale: change the scale

The function called and calling table shows the relationship of the functions. The dologo function is invoked when the document is first loaded and then whenever the scale is changed.

Table 1-1. Functions in the HTML5 Logo project

Function Invoked / Called By Calls

init invoked by action of the onLoad attribute in the **** tag dologo

dologo init and changescale

changescale invoked by action of the onChange attribute in the **** tag dologo

The coding for the dologo function puts together the techniques previously described. In particular, the code brings back the original coordinate system and clears off the canvas. The global variables in this application are

var ctx; var factorvalue = 1; var fontfamily = "65px 'Gill Sans Ultra Bold', sans-serif";

As indicated earlier, it would be possible to not use the fontfamily but use the string directly in the code. It is convenient to make ctx and factorvalue global. Table 1-2 shows the code for the basic application, with comments for each line.

Table 1-2. Complete Code for the HTML5 Logo project

Code Line Description

**** header

**** opening html tag

**** opening head tag

**HTML5 Logo ** (^) complete title element

**** meta tag

**** close the style element

**

Code Line Description

ctx.fill(); fill in with the indicated color

// right hand, lighter orange part of the // background

ctx.fillStyle = "#F06529"; (^) set color to the official darker orange

ctx.beginPath(); (^) start the path

ctx.moveTo(139, 257); move to middle point, close to the top

ctx.lineTo(220, 234); draw line to the right and slightly up

ctx.lineTo(239, 20); draw line to the right and up

ctx.lineTo(139, 20); draw line to the left (point at the middle)

ctx.closePath(); close path

ctx.fill(); (^) fill in with the indicated color

//light gray, left hand side part of the //five

ctx.fillStyle = "#EBEBEB"; set color to gray

ctx.beginPath(); (^) start path

ctx.moveTo(139, 113); move to middle horizontally, midway vertically

ctx.lineTo(98, 113); draw line to the left

ctx.lineTo(96, 82); draw line up and slightly further left

ctx.lineTo(139, 82); draw line to right

ctx.lineTo(139, 51); draw line up

ctx.lineTo(62, 51); draw line to the left

Code Line Description

ctx.lineTo(70, 144); draw line to the left and down

ctx.lineTo(139, 144); draw line to the right

ctx.closePath(); (^) close path

ctx.fill(); fill in with indicated color

ctx.beginPath(); start a new path

ctx.moveTo(139, 193); (^) move to middle point

ctx.lineTo(105, 184); draw line to the left and up

ctx.lineTo(103, 159); draw line slightly to the left and up

ctx.lineTo(72, 159); draw line more to the left

ctx.lineTo(76, 207); draw line slightly to the right and down

ctx.lineTo(139, 225); draw line to the left and down

ctx.closePath(); (^) close path

ctx.fill(); fill in the shape in the indicated color

// white, right hand side of the 5

ctx.fillStyle = "#FFFFFF"; set color to white

ctx.beginPath(); (^) start path

ctx.moveTo(139, 113); start at middle pint

ctx.lineTo(139, 144); draw line down

ctx.lineTo(177, 144); draw line to the right

ctx.lineTo(173, 184); (^) draw line slightly left and down