HTML5 and JavaScript Projects

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.


Jeanine Meyer


443 Pages

39175 Reads

33 Downloads

English

PDF Format

7.82 MB

HTML Learning

Download PDF format


  • Jeanine Meyer   
  • 443 Pages   
  • 26 Feb 2015
  • Page - 1

    HTML5 and JavaScript Projects ■ ■ ■ Jeanine Meyer read more..

  • Page - 2

    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. read more..

  • Page - 3

    v Contents About the Author ....................................................................................................... xi About the Technical Reviewer .................................................................................. xii Acknowledgments ................................................................................................... xiii Introduction read more..

  • Page - 4

    ■ CONTENTS vi HTML5, CSS, and JavaScript features ............................................................................. 22 JavaScript objects .................................................................................................................................. 22 User interface ......................................................................................................................................... 31 Saving the read more..

  • Page - 5

    ■ CONTENTS vii Events ................................................................................................................................................... 109 Calculating Distance and Rounding Values for Display ........................................................................ 113 Building the Application and Making It Your Own ......................................................... 114 Testing and Uploading read more..

  • Page - 6

    ■ CONTENTS viii HTML5, CSS, JavaScript, and PHP Features .................................................................. 196 Geolocation ........................................................................................................................................... 196 Reverse Geocoding ............................................................................................................................... 200 Clicking the read more..

  • Page - 7

    ■ CONTENTS ix HTML5, CSS, JavaScript, and Programming Features . ................................................. 294 Acquiring the Images and Data for the Pieces . ................................................................................... 294 Dynamically Created Elements . ........................................................................................................... 295 Setting Up read more..

  • Page - 8

    ■ CONTENTS x ■Chapter 10: Web Site Database: Using PHP and MySQL ...................................... 367 Introduction ................................................................................................................... 367 Critical Requirements .................................................................................................... 376 SQL, PHP, HTML5, and JavaScript Features read more..

  • Page - 9

    xi 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 read more..

  • Page - 10

    xii About the Technical Reviewer ■Andrew Zack is the CEO of ZTMC (http://ztmc.com), 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 read more..

  • Page - 11

    xiii 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 read more..

  • Page - 12

    iv Contents at a Glance About the Author ....................................................................................................... xi About the Technical Reviewer .................................................................................. xii Acknowledgments ................................................................................................... xiii Introduction read more..

  • Page - 13

    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 read more..

  • Page - 14

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

  • Page - 15

    C H A P T E R 1 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 • read more..

  • Page - 16

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 2 ■ 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 read more..

  • Page - 17

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 3 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 read more..

  • Page - 18

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 4 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 read more..

  • Page - 19

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 5 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 read more..

  • Page - 20

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 6 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 read more..

  • Page - 21

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 7 </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 read more..

  • Page - 22

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 8 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; read more..

  • Page - 23

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 9 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 read more..

  • Page - 24

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 10 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 read more..

  • Page - 25

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 11 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 read more..

  • Page - 26

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 12 Table 1-2. Complete Code for the HTML5 Logo project Code Line Description <!DOCTYPE html> header <html> opening html tag <head> opening head tag <title>HTML5 Logo </title> complete title element <meta charset="UTF-8"> meta tag <style> read more..

  • Page - 27

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 13 Code Line Description } close function function dologo() { start of dologo function var offsety = 80 ; specify amount to adjust the coordinates to draw the shield part of the logo. ctx.restore(); restore original state of coordinates ctx.save(); save it read more..

  • Page - 28

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 14 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 read more..

  • Page - 29

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 15 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 read more..

  • Page - 30

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 16 Code Line Description ctx.lineTo(139, 193); draw line more left and down ctx.lineTo(139, 225); draw line down ctx.lineTo(202, 207); draw line to the right and up ctx.lineTo(210, 113); draw line slightly right and up ctx.closePath(); close path ctx.fill(); fill in read more..

  • Page - 31

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 17 Code Line Description <body onLoad="init();"> body tag with attribute set to invoke init <canvas id="canvas" width="600" height="400"> canvas tag setting dimensions and with id to be used in code Your browser does not support the canvas element. read more..

  • Page - 32

    CHAPTER 1 ■ BUILDING THE HTML5 LOGO - DRAWING ON CANVAS, WITH SCALING, AND SEMANTIC TAGS 18 Testing and uploading the application This is a simple application to test and upload (and test) because it is a single file. I am told that the logo does display on iPhone4 and iPad2, but the slider is a text box in each case. I also tested it read more..

  • Page - 33

    C H A P T E R 2 19 Family Collage: Manipulating Programmer-defined Objects on a Canvas In this chapter, you will learn about • Creating and manipulating object-oriented programming for drawing on canvas • Handling mouse events, including double-click • Saving the canvas to an image • Using try and catch read more..

  • Page - 34

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 20 Figure 2-1. Opening screen for Family Pictures Figure 2-2 shows what I, as an end-user, produced as a final product. I have arranged the photographs to represent my son's family, including my new granddaughter. I deleted the two rectangles and the oval and made duplicates of read more..

  • Page - 35

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 21 Figure 2-2. Sample final product: rearranged objects I decided on including a heart, not just for sentimental reasons, but because it required me to use algebra and geometry. Don't be afraid of mathematics. It is very useful. I invented, so to speak, a canonical read more..

  • Page - 36

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 22 objects. The current framework provides a way to specify rectangles, ovals, hearts and images, but the approach can accommodate other shapes and this is an important lesson of the chapter. The objective is for the drag and drop operations to be reasonably precise: not read more..

  • Page - 37

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 23 ■ Note Object oriented programming in all its glory has a rich and often daunting vocabulary. Classes are what define objects. I have hinted here at what is called an interface. Classes can be subclasses of other classes and this may have been useful for pictures and read more..

  • Page - 38

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 24 this.ver = ver; this.draw = drawoval; this.color = c; this.overcheck = overoval; } The x and y values refer to the center of the Oval. The hor and ver attributes will be used to scale the read more..

  • Page - 39

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 25 Setting up one of the Picture objects takes more work than Rect objects. I need to write the code to create an Image object. This is a built-in object type in JavaScript. I need to acquire an image file and move it into the same folder as the HTML read more..

  • Page - 40

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 26 Drawing I have the different method functions to explain, but let's go to where the drawing is done in order to demonstrate how all of this works together. I define an array, initially empty, var stuff = []; Then my code adds to this array with statements read more..

  • Page - 41

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 27 Then a scaling transformation is applied, using the hor and ver properties. Now, after setting the fillStyle to be the color specified in the color attribute, I use the coding for drawing a path made up of a circular arc and filling the path. The last step is to read more..

  • Page - 42

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 28 Figure 2-4. Added pieces of data used in functions The path will start at what we are calling the cleft or the cleavage (giggle) and draw the arc on the left, then draw a line to the bottom point, then up to the cx,cy point and then finish with read more..

  • Page - 43

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 29 function overrect (mx,my) { if ( (mx>=this.x)&&(mx<=(this.x+this.w))&&(my>=this.y)&&(my<=(this.y+this.h))) {return true;} else {return false;} } The function defining the overcheck method for ovals read more..

  • Page - 44

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 30 function overheart(mx,my) { var leftctrx = this.x-this.drx; var rightctrx = this.x+this.drx; var qx = this.x-2*this.drx; var qy = this.y-this.drx; var qwidth = 4*this.drx; var qheight read more..

  • Page - 45

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 31 ■ Note This example does not demonstrate the full power of object-oriented programming. In a language such as Java (or the variant Processing designed for artists), I could have programmed this in such a way to check that each additional object was defined properly, that is read more..

  • Page - 46

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 32 The makenewitem and the startdragging functions start off the same. The code first determines the mouse cursor coordinates and then loops through the stuff array to determine which, if any, object was clicked on. You probably have seen the mouse cursor coordinate code read more..

  • Page - 47

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 33 So the effect of the two functions is to duplicate whatever element is under the mouse cursor. You or your end-user can then mouse down on the original or the cloned object and move it around. The startdragged function proceeds as indicated to determine what read more..

  • Page - 48

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 34 function moveit(ev) { var mx; var my; if ( ev.layerX || ev.layerX == 0) { mx= ev.layerX; my = ev.layerY; } else read more..

  • Page - 49

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 35 function saveasimage() { try { window.open(canvas1.toDataURL("image/png"));} catch(err) { alert("You need to change browsers OR upload the file to a server."); } } Building the application and making it your own You can make this application read more..

  • Page - 50

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 36 Continued Function Invoked / Called By Calls drawrect invoked in drawstuff drawoval invoked in drawstuff drawpic invoked in drawstuff overheart invoked in startdragging and makenewitem distsq, outside overrect invoked in startdragging and makenewitem overoval invoked in read more..

  • Page - 51

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 37 Table 2-2. Complete Code for the HTML5 Logo project Code Line Description <!DOCTYPE html > standard heading for HTML5 documents <html> html tag <head> head tag <title>Build family picture</title> complete title <meta charset="UTF-8"> meta tag <style> start of style read more..

  • Page - 52

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 38 Code Line Description canvas1 = document.getElementById('canvas'); sets variable to reference the canvas element canvas1.onmousedown = function () { return false; } ; prevents change of cursor to default canvas1.addEventListener('dblclick',makenewitem,false); sets up the read more..

  • Page - 53

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 39 Code Line Description var pic2 = new Picture(120,100,100,100,mom); constructs a Picture object var pic3 = new Picture(230,100,100,100,son1); constructs a Picture object var pic4 = new Picture(340,100,100,100,son2); constructs a Picture read more..

  • Page - 54

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 40 Code Line Description function Picture(x,y,w,h,imagename) { function header for Picture constructor, positioned at x, y, with width w and height h, and the imagename Image object. this.x = x; set attribute this.y = y; set attribute read more..

  • Page - 55

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 41 Code Line Description this.overcheck = overheart; set overheart function to be the overcheck method this.ang = .25*Math.PI; set attribute to be this constant value. May make more general at a later time } close function function drawheart() { read more..

  • Page - 56

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 42 Code Line Description ctx.fill(); fill in path } close function function overheart(mx,my) { header for overheart function var leftctrx = this.x-this.drx; set variable to be x coordinate of center of left curve var rightctrx = read more..

  • Page - 57

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 43 Code Line Description var m = (this.h)/(2*this.drx); calculate slope of left line if (mx<=this.x) { If mx is on the left side… if (my < (m*(mx-x2)+y2)) {return true;} compare my to the y value corresponding to mx. If my is above (on the read more..

  • Page - 58

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 44 Code Line Description function Oval(x,y,r,hor,ver,c) { function header for Oval constructor, position x, y, horizontal scaling hor, vertical scaling ver, color c. this.x = x; set attribute this.y = y; set attribute this.r = r; read more..

  • Page - 59

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 45 Code Line Description ctx.restore(); restore original coordinate state } close function function Rect(x,y,w,h,c) { function header Rect constructor: position x,y, width w and height h, color c. this.x = x; set attribute this.y read more..

  • Page - 60

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 46 Code Line Description } end clause else {return false} else return false } close function function overrect (mx,my) { function header for overrect if ( (mx>=this.x)&&(mx<=(this.x+this.w))&&(my>=this.y) read more..

  • Page - 61

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 47 Code Line Description var item; will hold the new item for (var i=endpt;i>=0;i--) { start search from the end if (stuff[i].overcheck(mx,my)) { is the mouse over this member of stuff read more..

  • Page - 62

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 48 Code Line Description var mx; variable will hold x coordinate of mouse var my; variable will hold y coordinate of mouse if ( ev.layerX || ev.layerX == 0) { // Firefox, ??? does this browser use layer… read more..

  • Page - 63

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 49 Code Line Description canvas1.addEventListener('mousemove', moveit,false); set up event handling for moving the mouse canvas1.addEventListener('mouseup',dropit, false); set up event handling for releasing mouse button read more..

  • Page - 64

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 50 Code Line Description mx = ev.offsetX; …set mx my = ev.offsetY; … set my } end clause stuff[thingInMotion].x = mx-offsetx; set x for the thingInMotion, read more..

  • Page - 65

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 51 Code Line Description function saveasimage() { function header for saveasimage try { start try clause window.open(canvas1.toDataURL("image/png"));} create the image data and use it as contents of new window catch(err) { if that didn't work, that is, threw an error read more..

  • Page - 66

    CHAPTER 2 ■ FAMILY COLLAGE - MANIPULATING PROGRAMMER-DEFINED OBJECTS ON A CANVAS 52 Code Line Description <button onClick="saveasimage();">Open window with image (which you can save into image file) </button></br> button for saving image <button onClick="removeobj();">Remove last object moved </button> button for removing object </body> close body read more..

  • Page - 67

    C H A P T E R 3 53 Bouncing Video: Animating and Masking HTML5 Video In this chapter, you will learn how to do the following: • Produce a moving video clip by drawing the current frame of the video at different locations on a canvas • Produce a moving video clip by repositioning the video element read more..

  • Page - 68

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 54 Figure 3-1. Screen capture, full window In all cases, when the virtual ball hits a wall, it appears to bounce off the wall. If, for example, the virtual ball is moving down the screen and to the right, when it hits the right side of the box, it will head off to the read more..

  • Page - 69

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 55 Figure 3-2. Trajectory of virtual ball If I resize the browser window to be a little bit smaller and reload the application, the code will resize the canvas to produce what is shown in Figure 3-3: a smaller box. read more..

  • Page - 70

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 56 Figure 3-3. Application in smaller window If the window is made very small, this forces a change in the size of the video clip itself, as well as the canvas and the box, as shown in Figure 3-4. read more..

  • Page - 71

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 57 Figure 3-4. Window resized to very small The application adapts the box size, and possibly the virtual video ball size, to the window dimensions at the time that the HTML document is first loaded. If the window is resized by the viewer later, during the running of the application, the canvas and video read more..

  • Page - 72

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 58 Similarly, if you start the application using a full-size window, or any large window, and resize it to something smaller during the running of the program, you would see something like Figure 3-6, where the scroll bars are displayed by the browser to indicate that the content of the read more..

  • Page - 73

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 59 same thing. My explanation of the coding is complete in this chapter. However, if the first book is available to you (shameless plug), you may benefit from seeing what is the same and what is different among the various versions. In the ball and image applications, the canvas read more..

  • Page - 74

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 60 Video Converter, downloadable from www.mirovideoconverter.com/, is a good product to convert a video clip into other formats. With that reminder, I can present the body element for this application. It contains a video element, a button, and a canvas element: <body onLoad="init();"> read more..

  • Page - 75

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 61 The ballrad variable is inherited from the previous applications. It is the radius of the ball, assuming the video height and width are equal and less than 50 pixels. Its use in the videobounce applications is to set the width of the line used to draw the box. The radius read more..

  • Page - 76

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 62 The objective of the moveandcheck function is to reposition the virtual ball by setting ballx and bally, and when appropriate, change the signs of ballvx and ballvy. The way the code works is to try out new values (see nballx and nbally in the function) and then set read more..

  • Page - 77

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 63 function moveandcheck() { var nballx = ballx + ballvx; var nbally = bally + ballvy; if ((nballx+videow) > cwidth) { ballvx =-ballvx; nballx = cwidth-videow; } if (nballx < 0) { nballx = 0; ballvx read more..

  • Page - 78

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 64 To avoid this, you will see that I changed the checking for the video element application. The downside to doing this is that the video ball barely touches the right and bottom walls. The reason why these effects do not happen in the video-drawn-on-canvas application, videobounceC, read more..

  • Page - 79

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 65 #vid {position:absolute; display:none; } #canvas {position:absolute; z-index:10; top:0px; left:0px;} #revbtn {position:absolute; z-index:20; } A way to remember how the layering works is to think of the z-axis as coming out of the screen. Elements set at higher values are on top of elements set at read more..

  • Page - 80

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 66 v.style.left = String(ballx)+"px"; v.style.top = String(bally)+"px"; v.play(); v.style.visibility = "visible"; v.style.display = "block"; is executed in the init function. Notice also that read more..

  • Page - 81

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 67 Figure 3-8. Outline of paths for the mask Figure 3-9 shows the outline and the paths filled in. Figure 3-9. Paths for the mask after a fill and a stroke Now, the actual path only has the fill, and the fill color is white. You need to imagine these two white shapes traveling along on read more..

  • Page - 82

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 68 ctx.moveTo(ballx,bally+.5*videoh); ctx.lineTo(ballx,bally+videoh); ctx.lineTo(ballx+videow,bally+videoh); ctx.lineTo(ballx+videow,bally+.5*videoh); ctx.lineTo(ballx+.5*videow+maskrad,bally+.5*videoh); ctx.arc(ballx+.5*videow,bally+.5*videoh,maskrad,0,Math.PI,false); ctx.lineTo(ballx,bally+.5*videoh); ctx.fill(); You can follow along the coding read more..

  • Page - 83

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 69 1. init: initialization, including adapting to fit the window and setting up the timed event for invoking drawscene 2. drawscene: a. Erase the canvas. b. Determine new location of video (virtual ball) using moveandcheck. c. Either draw the image from video at a specified location read more..

  • Page - 84

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 70 Table 3-2. Complete Code for the VideobounceC Application Code Line Description <!DOCTYPE html> Header <html> Opening html tag <head> Opening head tag <title>Video bounce</title> Complete title <meta charset="UTF-8"> Meta element <style> Opening style #vid {position:absolute; read more..

  • Page - 85

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 71 Code Line Description var ballvy = 4; Initial ball vertical displacement var v; Will hold video element function restart() { Function header for restart v.currentTime=0; Reset place in video to the start v.play(); Play video } Close restart function function init(){ Function header for init read more..

  • Page - 86

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 72 Code Line Description ballrad = Math.min(50,.5*videow,.5*videoh); Modify ballrad if there is a very small video maskrad = .4*Math.min(videow,videoh); Set maskrad based on video dimensions ctx.lineWidth = ballrad; Set line width for drawing the box ctx.strokeStyle ="rgb(200,0,50)"; read more..

  • Page - 87

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 73 Code Line Description ctx.lineTo(ballx,bally+.5*videoh); Move to the left ctx.lineTo(ballx,bally); Move to start ctx.fill(); Fill in the white top of the mask ctx.moveTo(ballx,bally+.5*videoh); Move to start the bottom of the mask; move to point midway down on the left read more..

  • Page - 88

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 74 Code Line Description } Close clause if (nballx < 0) { Compare to left wall, on a hit nballx = 0; Set trial value to be exactly at the left wall ballvx = -ballvx; Change sign of the horizontal displacement } Close clause if (nbally read more..

  • Page - 89

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 75 Code Line Description ballvy = -ballvy; Change sign of vertical displacement } Close reverse function </script> Closing script tag </head> Closing head tag <body onLoad="init();"> Opening body tag; set up call to init <video id="vid" loop="loop" read more..

  • Page - 90

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 76 Table 3-3. Complete Code for the VideobounceE Program Code Line Description <!DOCTYPE html> <html> <head> <title>Video bounce</title> <meta charset="UTF-8"> <style> #vid {position:absolute; display:none; z-index: 1; Need to set positioning and z-index because read more..

  • Page - 91

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 77 Code Line Description var ballvy = 4; var v; function restart() { v.currentTime=0; v.play(); } function init(){ canvas1 = document.getElementById('canvas'); ctx = canvas1.getContext('2d'); canvas1.width = window.innerWidth; cwidth = canvas1.width; canvas1.height = window.innerHeight; cheight = read more..

  • Page - 92

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 78 Code Line Description ballrad = Math.min(50,.5*videow,.5*videoh); maskrad = .4*Math.min(videow,videoh); ctx.lineWidth = ballrad; ctx.strokeStyle ="rgb(200,0,50)"; ctx.fillStyle="white"; v.style.left = String(ballx)+"px"; v.style.top = String(bally)+"px"; read more..

  • Page - 93

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 79 Code Line Description ctx.arc(ballx+.5*videow,bally+.5*videoh,maskrad,0, Math.PI,true); ctx.lineTo(ballx,bally+.5*videoh); ctx.lineTo(ballx,bally); ctx.fill(); ctx.moveTo(ballx,bally+.5*videoh); ctx.lineTo(ballx,bally+videoh); ctx.lineTo(ballx+videow,bally+videoh); ctx.lineTo(ballx+videow,bally+.5*videoh); read more..

  • Page - 94

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 80 Code Line Description } if (nballx < 0) { nballx = 0; ballvx = -ballvx; } if ((nbally+videoh) > cheight) { Compare total length nbally = cheight-videoh; Set to exact position ballvy =-ballvy; Change sign of vertical read more..

  • Page - 95

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 81 Code Line Description <body onLoad="init();" > <video id="vid" loop="loop" preload="auto"> <source src="joshuahomerun.webmvp8.webm" type='video/webm; codec="vp8, vorbis"'> <source src="joshuahomerun.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> read more..

  • Page - 96

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 82 Table 3-4. Complete code for VideobounceTrajectory Program Code Line Description <!DOCTYPE html> <html> <head> <title>Video bounce</title> <meta charset="UTF-8"> <style> #canvas {position:absolute; z-index:10; top:0px; left:0px;} #revbtn {position:absolute; z-index:20; } read more..

  • Page - 97

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 83 Code Line Description ctx = canvas1.getContext('2d'); canvas1.width = window.innerWidth; cwidth = canvas1.width; canvas1.height = window.innerHeight; cheight = canvas1.height; videow= Math.min(106,.5*cwidth); Use values of actual video width videoh = read more..

  • Page - 98

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 84 Code Line Description ctx.fill(); Fill in (this will be white) ctx.stroke(); Set red stroke (outline) ctx.lineWidth= ballrad; Set line width for the box ctx.strokeRect(0,0,cwidth,cheight); Draw the box } function moveandcheck() { var nballx = ballx + read more..

  • Page - 99

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 85 Code Line Description ballvy = -ballvy; } ballx = nballx-.5*videow; bally = nbally-.5*videoh; } function reverse() { ballvx = -ballvx; ballvy = -ballvy; } </script> </head> <body onLoad="init();"> <button id="revbtn" read more..

  • Page - 100

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 86 HTML5. Another set of enhancements would be to add video controls. Video controls can be part of the video element, but I don’t think that would work for a video clip that needs to be small and is moving! However, you could implement your own controls with buttons read more..

  • Page - 101

    CHAPTER 3 ■ BOUNCING VIDEO: ANIMATING AND MASKING HTML5 VIDEO 87 Summary In this chapter, you learned different ways to manipulate video. These included the following: • Drawing the current frame of video as an image onto a canvas • Repositioning of a video element on the screen by changing the left and top style attributes • Using style directives to read more..

  • Page - 102

    C H A P T E R 4 89 Map Maker: Combining Google Maps and the Canvas In this chapter, you will learn how to do the following: • Use the Google Maps API to display a map at a specific location • Draw graphics on a canvas using transparency (also known as the alpha or opacity level) and a read more..

  • Page - 103

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 90 Figure 4-1. Opening screen of map spotlight project Notice the small red (hand-drawn) x located just above and to the left of SoHo. When deciding on map markers, you face a trade-off. A smaller marker is more difficult to see. A larger and/or more intricate marker is easier to read more..

  • Page - 104

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 91 Figure 4-2. Shadow/spotlight over map Notice the shadow and spotlight combination now on the map. Most of the map is covered by a semitransparent shadow. You need to trust me that this screenshot was taken when I had moved the mouse over the map. There is a circle around read more..

  • Page - 105

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 92 Figure 4-3. Zoomed in to street level It also is possible to pan the map by clicking the hand in the upper-left corner and then virtually grabbing the mouse by pressing down on the mouse button and pulling. Figure 4-4 shows the effects of zooming out and moving north. The read more..

  • Page - 106

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 93 Figure 4-4. Zooming out and moving north The program provides a way to change the base location. There are three choices: the location of the publisher, friends of ED, in New York City; Purchase College (where I teach), located in Purchase, New York, which is north of New York read more..

  • Page - 107

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 94 Figure 4-5. Purchase College new base location Next, I switch to Illinois Institute of Technology in Chicago, Illinois, as the base by clicking the third radio button. The result is shown in Figure 4-6. read more..

  • Page - 108

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 95 Figure 4-6. Base at Illinois Institute of Technology in Chicago Again, notice the small red x indicating the base location and the text at the top of the screen with the name of the new base location. The location of each base is determined by the latitude and read more..

  • Page - 109

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 96 Figure 4-7. Farthest-out view of map Figure 4-8 shows the map at close to the closest-in limit. The map has also been changed to the satellite view using the buttons in the upper-right corner. read more..

  • Page - 110

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 97 Figure 4-8. Zoomed in to where city blocks can be detected Notice that the slider on the left is about four notches above the closest setting. Lastly, Figure 4-9 shows the map zoomed in to the limit. This is essentially at the building level, at least for Manhattan. read more..

  • Page - 111

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 98 Figure 4-9. Zoomed in all the way By using the interface to zoom out and pan and zoom in again, I can determine the distance from any of the base locations to any other location in the world! I also can use this application to determine latitude and longitude values of any location. You need to read more..

  • Page - 112

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 99 planet earth. The latitude and longitude system has been developed and standardized over the last several hundred years. The values are angles, with latitude indicating degrees from the equator and longitude indicating degrees from the Greenwich prime meridian in the United Kingdom. The latter is an read more..

  • Page - 113

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 100 Figure 4-10. Getting latitude longitude values in Google Maps After choosing the Drop LatLng Marker option, you will see the latitude and longitude values in a small box, as shown in Figure 4-11. Figure 4-11. Box showing latitude and longitude read more..

  • Page - 114

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 101 Another option is to use Wolfram Alpha (www.wolframalpha.com), as shown in Figure 4-12, which provides a way to determine latitude and longitude values as well as many other things. Figure 4-12. Results of query on Wolfram Alpha Notice the format of the results. This is read more..

  • Page - 115

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 102 Notice that the longitude still appears with W for West as opposed to the negative value given by Google Maps. Doing what I call “going in the opposite direction,” you can put latitude and longitude values into Google Maps. Figure 4-14 shows the results of putting in 0.0 read more..

  • Page - 116

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 103 Figure 4-15. Results near a place on the Greenwich prime meridian The A marker indicates the closest place in the Google database to the requested location. I used the Drop LatLng marker option to reveal the exact latitude and longitude values. The critical requirements for this project read more..

  • Page - 117

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 104 These are the critical requirements for the map spotlight project. Now I will explain the HTML5 features I used to build the project. The objective is to use Google Maps features and JavaScript features, including events, and not let them interfere with each other. You can use what you learn read more..

  • Page - 118

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 105 ■ Note Though I try to use the language “bring access to Google Maps into the HTML document,” I am guilty of describing a function that “makes” a map. The Google Maps connection is a dynamic one in which Google Maps creates what are termed “tiles to be displayed.” The second read more..

  • Page - 119

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 106 • The exact shape of this mask varies. The outer boundary is the whole canvas, and the location of the hole is aligned with the current position of the mouse. The hole moves around. • The color of the mask is not solid paint, but a transparent gray. The canvas starts out read more..

  • Page - 120

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 107 Figure 4-17 shows another example of the shadow mask drawn on the same map. This came about because of movement of the mouse by the user. Figure 4-17. Shadow mask over another position on the map Several topics are interlinked here. Let’s assume that the variables mx read more..

  • Page - 121

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 108 The function drawshadowmask makes use of several variables that are constants—they never change. A schematic indicating the values is shown in Figure 4-18. Figure 4-18. Schematic with variable values indicated for mask The mask is drawn in two parts as was done for the mask for the bouncing video. You read more..

  • Page - 122

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 109 ctx.lineTo(canvasAx,my); ctx.closePath(); ctx.fill(); } Now we move on to the red lightbulb. Cursor The cursor—the small graphic that moves on the screen when you move the mouse—can be set in the style element or in JavaScript. There are several built-in choices for the read more..

  • Page - 123

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 110 function showshadow(ev) { var mx; var my; if ( ev.layerX || ev.layerX == 0) { mx= ev.layerX; my = ev.layerY; } else if (ev.offsetX || ev.offsetX == 0) { mx = ev.offsetX; read more..

  • Page - 124

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 111 The call to addListener, a method that is part of the Google Maps API as opposed to JavaScript proper, sets up the call to the checkit function. The checkit function is invoked using an attribute of the event object as a parameter. As you can guess, event.latLng is read more..

  • Page - 125

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 112 function checkit(clatlng) { var distance = dist(clatlng,blatlng); distance = round(distance,2); var distanceString = String(distance)+" km"; marker = new google.maps.Marker({ position: clatlng, title: distanceString, icon: bxmarker, map: map }); var read more..

  • Page - 126

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 113 Calculating Distance and Rounding Values for Display Google Maps, as many of us know, provides information on distances and even distinguishes between walking and driving. For this application, I needed more control on specifying the two locations for which I wanted the distance calculated, so read more..

  • Page - 127

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 114 3. Calculates the largest whole number not bigger than the result (this is called the floor)—producing a whole number 4. Divides the result by the factor The code follows: function round (num,places) { var factor = Math.pow(10,places); var increment = read more..

  • Page - 128

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 115 Table 4-1. Functions in the Map Maker Project Function Invoked/Called By Calls init Invoked by action of the onLoad attribute in the <body> tag makemap pushcanvasunder Invoked by action of addEventListener called in init clearshadow Invoked by action of addEventListener called in read more..

  • Page - 129

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 116 Code Line Description display:block; } Line breaks before and after canvas {position:absolute; top: 165px; left:0px; Style directive for the single canvas element: position slightly down the page z-index:100;} Initial setting for canvas is on top of map #place {position:absolute; top: read more..

  • Page - 130

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 117 Code Line Description var ctx; Reference context of canvas; used for all drawing var pl; Reference the div holding the Google Map function init() { Function header for init var mylat; Will hold latitude value var mylong; Will hold longitude value candiv = read more..

  • Page - 131

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 118 Code Line Description mylong = locations[0][1]; Set the longitude to be the longitude of the 0th location makemap(mylat,mylong); Invoke function to make a map (bring in Google Maps at specified location) } Close init function function pushcanvasunder(ev) { Header for pushcanvas function, called with parameter read more..

  • Page - 132

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 119 Code Line Description mx = ev.layerX; If so, use it to set mx . . . my = ev.layerY; . . . and my } else if (ev.offsetX || ev.offsetX == 0) { Try offsetX mx = ev.offsetX; If so, use it to set mx . . read more..

  • Page - 133

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 120 Code Line Description var canvasDy = 400; Lower-left y var holerad = 50; Constant radius for hole in shadow (radius of spotlight) var grayshadow = "rgba(250,250,250,.8)"; Color for faint shadow; note alpha of .8 function drawshadowmask(mx,my) { Header for drawshadowmask function; parameters read more..

  • Page - 134

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 121 Code Line Description ctx.lineTo(canvasDx,canvasDy); Draw to lower-left corner ctx.lineTo(canvasCx,canvasCy); Draw to lower-right corner ctx.lineTo(canvasBx,my); Draw to point on right edge ctx.lineTo(mx+holerad,my); Draw to left to edge of hole ctx.arc(mx,my,holerad,0,Math.PI,false); Draw read more..

  • Page - 135

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 122 Code Line Description blatlng = new google.maps.LatLng(mylat,mylong); Build a LatLng object (special data type for the API) myOptions = { Set associative array zoom: 12, Zoom setting (can be 0 to 18) center: blatlng, Center mapTypeId: read more..

  • Page - 136

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 123 Code Line Description 'mouseup', The specific event function(event) { An autonomous function (defined directly as a parameter in addListener) checkit(event.latLng); Calling checkit with the indicated latitude longitude object read more..

  • Page - 137

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 124 Code Line Description map: map Set map element of associative array to the value of the variable named map } Close associative array ); Close call to Marker method var clat = clatlng.lat(); Extract the latitude value var read more..

  • Page - 138

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 125 Code Line Description function dist(point1, point2) { Function header for dist (distance) function // spherical law of cosines, // from // http://www.movable- type.co.uk/scripts/latlong.html Attribution for my source. This is standard mathematics var R = 6371; // km read more..

  • Page - 139

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 126 Code Line Description if (document.f.loc[i].checked) { Is this one checked? mylat = locations[i][0]; If so, set mylat mylong = locations[i][1]; Set mylong read more..

  • Page - 140

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 127 Code Line Description <input type="radio" name="loc" /> Illinois Institute of Technology<br/> Radio button choice <input type="submit" value="CHANGE"> The button to make the change </form> Closing form tag </body> Closing body tag </html> Closing html tag read more..

  • Page - 141

    CHAPTER 4 ■ MAP MAKER: COMBINING GOOGLE MAPS AND THE CANVAS 128 The next chapter describes another project using Google Maps. You will learn how to build an application in which you can associate a picture, a video clip, or a picture-and-audio-clip combination with specific geographic locations, and display and play the specified media when a user clicks at or near the read more..

  • Page - 142

    C H A P T E R 5 129 Map Portal: Using Google Maps to Access Your Media In this chapter, you will explore the following: • Using the Google Maps API to play and display video, audio, and images • Creating HTML5 markup dynamically • Separating the program from descriptions of content • Building read more..

  • Page - 143

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 130 Table 5-1. Outline of Content Description of Location Media Purchase College Video from robotics class Mount Kisco Picture of Esther and an audio file of her playing piano Dixon, Illinois Picture of Aviva Statue of Liberty, New York City Video of fireworks All three read more..

  • Page - 144

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 131 Figure 5-1. Opening screen Figure 5-2 shows what happens when I click the screen on the Purchase College campus. A video clip appears and starts playing. You also can see “Lego robot” in the title position. Figure 5-2. Result of clicking at Purchase College Figure 5-3 read more..

  • Page - 145

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 132 Figure 5-3. Click not close to any target Figure 5-4 shows the result of my clicking near enough to Mt. Kisco to get a reward. I needed to move further north to get to Mt. Kisco. Notice also the audio control, providing a way to pause and resume playing and also read more..

  • Page - 146

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 133 Because I know where the locations are, I know to zoom out to get to the next location. Figure 5-5 shows the results of using the Google Maps interface to accomplish this. The audio track continues playing and I still see the picture. Figure 5-5. Zooming out in read more..

  • Page - 147

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 134 Again, I know where the pictures are, so I zoom out, pan to the west of Chicago, and click the small town of Dixon, Illinois. Figure 5-7 shows the image I expected. Figure 5-7. Panning to the west and zooming in to Dixon, Illinois It actually took some work (to be read more..

  • Page - 148

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 135 The question is, Where does Grandma Esther live? The player must click close to the location associated with this question. You might be able to guess the answer from the previous screenshots. Figure 5-9 shows an incorrect response. I just clicked the map near Purchase College. read more..

  • Page - 149

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 136 When designing a game such as this one, it is best to take pity on a player when they don’t know the answer. I provide the Hint? button, though it goes beyond just giving a hint. Skipping ahead, I will get the next two questions correct, and then I will need help on finding read more..

  • Page - 150

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 137 It is still necessary to click the map, hopefully on or near the red x, to complete the question. You may say that there are better ways of hinting—such as supplying specifically chosen text holding the name of the place—and I won’t argue with you. This is what I read more..

  • Page - 151

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 138 Google Maps API for Map Access and Event Handling Access to the Google Maps API requires a script element with reference to an external file. For this application, I used <script type="text/javascript" charset="UTF-8" src="http://maps.google.com/maps/api/js?sensor=false"></script> I set read more..

  • Page - 152

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 139 Figure 5-13. TERRAIN map type Figure 5-14 shows the results of requesting the HYBRID view, combining satellite and road map imagery. mapTypeId: google.maps.MapTypeId.HYBRID Figure 5-14. HYBRID map type read more..

  • Page - 153

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 140 By the way, the hybrid map is what is produced by clicking the Satellite option on the interface. Figure 5-15 shows the results of requesting SATELLITE images. mapTypeId: google.maps.MapTypeId.SATELLITE Figure 5-15. SATELLITE map type Lastly, you may have an application in which you read more..

  • Page - 154

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 141 Figure 5-16. Map interface removed There are two more operations for makemap to carry out. A custom marker is placed on the map at the indicated center location and event handling is set up for clicking the map: marker = new google.maps.Marker({ position: read more..

  • Page - 155

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 142 specifies four locations, starting with a picture/audio combination, followed by two videos, followed by one picture. The element in the array for the picture/audio combination includes, as you would expect, two additional pieces of information. It is not obvious from just this section read more..

  • Page - 156

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 143 video {display:none; position:relative; } audio {display:none; position:relative;} I did not have to do something analogous for the canvas. The canvas is always present, but if nothing has been drawn on it or it has been cleared, then nothing is visible. The critical coding for presenting read more..

  • Page - 157

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 144 Note that there is no harm in clearing the canvas even if there was nothing drawn on it. There would be an error in the statement v.pause(); if v was not set. For the quiz project, I put this code into its own function, which I named eraseold, because removing the old read more..

  • Page - 158

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 145 else { answer.innerHTML="Not close enough to any [new] target"; } } Regular Expressions Regular expressions are a powerful facility for describing patterns of character strings (text) for checking and for manipulation. It read more..

  • Page - 159

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 146 I could and probably should have made even more use of regular expressions to verify the data defining the content of the applications. Maybe that’s something you want to experiment with in your own applications. External Script File For this project and the one in the previous chapter, read more..

  • Page - 160

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 147 ■ Note At some point, the right decision may be to stop using straight JavaScript arrays, including the use of parallel structures, and make use of XML or a database. I didn't think it was called for in this application, but I could be wrong. Note that the use of databases does read more..

  • Page - 161

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 148 for (var i=0;i<precontent.length;i++) { content.push(precontent[i]); name = precontent[i][4]; The next line is the header of a switch statement using as the condition the element of the inner arrays that indicates the type. switch read more..

  • Page - 162

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 149 savedimagefilename = content[i][5]; content[i][5] = audioreference; imageobj = new Image(); read more..

  • Page - 163

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 150 it is determined that the s and i elements are to change locations. Two variables, hold and holdq, are the extra places used in the swap operation. function shufflecontent() { var i=content.length-1; var s; var hold; var read more..

  • Page - 164

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 151 3. checkit: Compares the clicked location with the locations described in the content array. If one is close enough, then the associated media is shown and played. 4. dist: Computes the distance between two locations. Table 5-2 outlines the functions in the mapvideos project. read more..

  • Page - 165

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 152 } Close style directive video {display:none; position:relative; } Style directive for video audio {display:none; position:relative;} Style directive for audio; note that this is for the controls </style> Closing style tag <script type="text/javascript" charset="UTF-8" read more..

  • Page - 166

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 153 var aud1; Set in init to the audio element var content; Declared here as global variable; will be set in init var answer; Will be set in init to reference a div in the body var v; reference to current (last) video var audioel; Reference to current (last) audio var base= read more..

  • Page - 167

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 154 } Close init function var xmarker = "x1.png"; Set file address for marker on the map function makemap(mylat,mylong) { Header for makemap function; map to be centered (mylat,mylong) var marker; Holds the constructed marker blatlng = new read more..

  • Page - 168

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 155 var latlnga =new google.maps.LatLng(content[0][0],content[0][1]); Build latitude/longitude object from first element of content var bestyet = 0; Will point to the index determined to be the best (closest) so far var closestdistance = read more..

  • Page - 169

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 156 audioel.pause(); Pause it audioel.style.display = "none"; Erase controls for last audio played } Close if audio clause ctx.clearRect(0,0,300,300); Clear canvas if (distance < maxdistance) { Is read more..

  • Page - 170

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 157 if (content[bestyet][3]=="picture") { If it is picture . . . break;} . . . leave the switch else { Else (for the picture/audio combination) read more..

  • Page - 171

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 158 var lon2 = point2.lng()*Math.PI/180; Change to radians var d = Math.acos(Math.sin(lat1)*Math.sin(lat2) + Math.cos(lat1)*Math.cos(lat2) * Math.cos(lon2-lon1)) * R; Calculation based on spherical law of cosines return d; Return result } Close dist function </script> Closing read more..

  • Page - 172

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 159 <video id="fire" preload="auto" controls="controls"> Video tag <source src="sfire3.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> Possible source <source src="sfire3.theora.ogv" type='video/ogg; codecs="theora, vorbis"'> Possible source <source read more..

  • Page - 173

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 160 The Mapmediabase Application The next application, mapmediabase.html, recreates the first application, but uses a separate file for the content. You can easily make this one your own by changing the content. You need to obtain the latitude/longitude coordinates for your locations. To do so, you read more..

  • Page - 174

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 161 Table 5-5. Complete Code for the Second Portal Application Code Line Description <!DOCTYPE html> <html> <head> <title>Clickable map </title> <meta charset="UTF-8"> <style> header {font-family:Georgia,"Times New Roman",serif; font-size:20px; read more..

  • Page - 175

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 162 Code Line Description var listener; var map; var myOptions; var ctx; var blatlng; var content = []; var answer; var v; var audioel; var videotext1 = "<video id=\"XXXX\" preload=\"auto\" controls=\"controls\" width=\"400\"><source src=\"XXXX.mp4\" read more..

  • Page - 176

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 163 Code Line Description loadcontent(); Invoke loadcontent to perform the rest of the initialization } function loadcontent() { Header for loadcontent function var divelement; Used to hold dynamically created div makemap(base[0],base[1]); Bring in read more..

  • Page - 177

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 164 Code Line Description name = precontent[i][4]; Extract the name switch (precontent[i][3]) { Switch over the different types (video, picture, pictureaudio) case "video": For the video read more..

  • Page - 178

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 165 Code Line Description audiomarkup = audiomarkup.replace(/XXXX/g,name); Change the XXXX to the name given in precontent divelement.innerHTML = audiomarkup; Set the constructed text to be the HTML within the div document.body.appendChild(divelement); Add the div to the body audioreference = read more..

  • Page - 179

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 166 Code Line Description var xmarker = "x1.png"; Image for marker on map function makemap(mylat,mylong) { var marker; blatlng = new google.maps.LatLng(mylat,mylong); myOptions = { zoom: zoomlevel, Pick up this value from the external file read more..

  • Page - 180

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 167 Code Line Description var i; var latlnga =new google.maps.LatLng(content[0][0],content[0][1]); var bestyet = 0; var closestdistance = dist(clatlng,latlnga); var distance; for read more..

  • Page - 181

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 168 Code Line Description } if (audioel != undefined) { audioel.pause(); audioel.style.display = "none"; } switch (content[bestyet][3]) { case "video": read more..

  • Page - 182

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 169 Code Line Description audioel = content[bestyet][5]; audioel.style.display="block"; audioel.currentTime = 0; audioel.play(); read more..

  • Page - 183

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 170 Code Line Description } </script> </head> <body onLoad="init();"> <header id="header">Click on map.</header> <div id="place" style="float: left;width:50%; height:400px"></div> <div style="float: right;width:30%;height:400px"> <div read more..

  • Page - 184

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 171 3. makemap: Brings in the map and sets up event handling, including the call to checkit. 4. shufflecontent: Shuffles the content and questions arrays (keeping them in correspondence). 5. asknewquestion: Displays the questions. 6. checkit: Compares the clicked location with the location read more..

  • Page - 185

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 172 Table 5-7. Include Table Caption Code Line Description <!DOCTYPE html> <html> <head> <title>Map Quiz </title> <meta charset="UTF-8"> <style> header {font-family:Georgia,"Times New Roman",serif; font-size:20px; display:block; read more..

  • Page - 186

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 173 Code Line Description <script type="text/javascript" charset="UTF-8"> var listener; var map; var myOptions; var ctx; var blatlng; var content = []; var answer; var v; var audioel; var videotext1 = "<video id=\"XXXX\" preload=\"auto\" read more..

  • Page - 187

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 174 Code Line Description ctx = document.getElementById("canvas").getContext('2d'); answer = document.getElementById("answer"); header = document.getElementById("header"); loadcontent(); shufflecontent(); Invoke function to shuffle order of questions read more..

  • Page - 188

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 175 Code Line Description holdq = questions[s]; Now, working on the questions array, save the sth element questions[s]=questions[i]; Swap in the ith element questions[i] = holdq; Put in the saved element read more..

  • Page - 189

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 176 Code Line Description var audiomarkup; var audioreference; var imageobj; var name; var savedimagefilename; for (var i=0;i<precontent.length;i++) { read more..

  • Page - 190

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 177 Code Line Description divelement.innerHTML = audiomarkup; document.body.appendChild(divelement); audioreference = document.getElementById(name); savedimagefilename = content[i][5]; content[i][5] = audioreference; imageobj = new Image(); imageobj.src= savedimagefilename; content[i][4] = imageobj; break; case read more..

  • Page - 191

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 178 Code Line Description myOptions = { zoom: zoomlevel, center: blatlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("place"), myOptions); marker = new google.maps.Marker({ position: blatlng, title: "center", icon: xmarker, map: map }); read more..

  • Page - 192

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 179 Code Line Description function checkit(clatlng) { var latlnga =new google.maps.LatLng(content[nextquestion][0],content[nextquesti on][1]); Build the latitude/longitude object for the answer to this question var distance = dist(clatlng,latlnga); Compute distance read more..

  • Page - 193

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 180 Code Line Description ctx.drawImage(content[nextquestion][4],10,10); if (content[nextquestion][3]=="picture") { break;} else { audioel = content[nextquestion][5]; audioel.style.display="block"; audioel.currentTime = 0; read more..

  • Page - 194

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 181 Code Line Description var lat2 = point2.lat()*Math.PI/180 ; var lon1 = point1.lng()*Math.PI/180; var lon2 = point2.lng()*Math.PI/180; var d = Math.acos(Math.sin(lat1)*Math.sin(lat2) + Math.cos(lat1)*Math.cos(lat2) * Math.cos(lon2-lon1)) * R; read more..

  • Page - 195

    CHAPTER 5 ■ MAP PORTAL: USING GOOGLE MAPS TO ACCESS YOUR MEDIA 182 Code Line Description <div id="answer">Title will be placed here.</div> <p> </p> <canvas id="canvas" width="300" height="300" > Your browser doesn't recognize canvas </canvas> </div> </body> </html> Testing and Uploading the read more..

  • Page - 196

    C H A P T E R 6 183 Where am I: Using Geolocation, the Google Maps API, and PHP In this chapter, you will learn the following: • How to use geolocation to determine the location of your users/customers/clients • About reverse geocoding in the Google Maps API to find the address of a given read more..

  • Page - 197

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 184 Figure 6-1. Opening screen with request for permission to share location (Firefox) The drop-down menu offers four options: Share Location, Always Share, Never Share, and Not Now. If you choose the first option, when you refresh the screen or return to the page, the program read more..

  • Page - 198

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 185 Figure 6-2. Opening screen with request for permission to share location (Opera) Notice that Opera gives the option of remembering the choice for this site. Figure 6-3 shows a follow-on screen that requests another confirmation that the user is opting-in. Figure read more..

  • Page - 199

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 186 Figure 6-4 shows the corresponding screen in Chrome. At this point, I had uploaded the application to one of my server accounts. The browser uses the domain name of the account in its query. Figure 6-4. Opening screen with request for permission to share location read more..

  • Page - 200

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 187 Figure 6-5. Request for permission to share location (Safari) Notice that Safari provides the user a way to give permission for 24 hours—that is, avoid repeated requests each day. Note that Safari on my desktop PC does not work, and unfortunately hangs up—does read more..

  • Page - 201

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 188 Figure 6-6. Request to share location (iPhone) There are many variables, which will be explained following, but in my recent experiment around my town, the iPhone returned the most accurate results. The permission is associated with the browser. For example, clicking “Remember my choice for read more..

  • Page - 202

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 189 Figure 6-7. Location found in the basic program The reverse geocoding has returned 100-162 E. Main Street, Mt. Kisco, NY 10549, USA for the description of the address with accuracy given as 86 meters. That is fairly accurate for the location of the red x. This read more..

  • Page - 203

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 190 Figure 6-8. Screen showing actual location The reverse geocoding is good: we were on Green Street. The program calculates and displays the distance from the base (the red x) and where I clicked (the black x). The location was .03 kilometers (equivalent to 30 meters). read more..

  • Page - 204

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 191 Figure 6-9. Opening screen for the e-mail program Notice that there is a form on display with a place to put From and To e-mail addresses. The subject line has the reverse-geocoding information, and the body of the message refers to the subject line. Next, I read more..

  • Page - 205

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 192 Figure 6-10. After clicking the location, the screen with information in the message body The clicked location now has the default marker used by Google Maps. This actually was an oversight on my part, but I decided to stick with it to show you that you can use read more..

  • Page - 206

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 193 I am satisfied with how this works, but what I have shown you so far appears to assume that my users/customers/clients will be well behaved and put in proper e-mail addresses. This is a bad assumption to make. To handle this, I declared form validation as a read more..

  • Page - 207

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 194 One can argue that it would be better if all the form input fields were validated at once, but that could lead to an overcrowded screen. We hope the user gets the message. If not, the messages will be repeated for the To field. The user may wonder about read more..

  • Page - 208

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 195 add to their databases. In any case, these databases are referenced to provide hot spot positions for the geolocation calculations. Your computer can use the signal strengths of neighboring hot spots to estimate its distances from them, get their locations from the databases, read more..

  • Page - 209

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 196 These are the requirements to build the projects demonstrated in the “Introduction” section. In the next section, I’ll describe the HTML5 and PHP features to implement the projects. HTML5, CSS, JavaScript, and PHP Features In this section, I will explain the features used to read more..

  • Page - 210

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 197 Figure 6-16. Internet Explorer request to run scripts After I gave permission, Internet Explorer showed that geolocation was not available (see Figure 6-17). Figure 6-17. Message on absence of geolocation in old Internet Explorer read more..

  • Page - 211

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 198 If the navigator.geolocation object does exist, then my code invokes the getCurrentPosition method with three parameters. The first parameter, handler, is the name of a function that will be invoked if and when the operation is complete. The second parameter, problemhandler, is invoked when there is read more..

  • Page - 212

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 199 Figure 6-18. Result of the user saying no to geolocation A subtler problem is the failure to perform the operation in a timely manner. Figure 6-19 shows the situation alluded to earlier concerning using Safari on a desktop computer. Figure 6-19. Geolocation taking read more..

  • Page - 213

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 200 Let’s move on now to the successful case: geolocation has worked. My code has caused the function handler to be invoked with the parameter set by the getCurrentPosition method to hold the calculated position information. The code extracts the latitude and longitude values read more..

  • Page - 214

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 201 It essentially is one statement, the call to geocode, which contains within the call the definition of a function. function reversegeo(latlng) { geocoder.geocode({'latLng': latlng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if read more..

  • Page - 215

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 202 Figure 6-20. The results array from geocoding The reason the second and third lines are identical may have to do with the fact that Mt. Kisco is a coterminous village and town. In any case, you may need to run a program with this sort of display to read more..

  • Page - 216

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 203 marker = new google.maps.Marker({ position: clatlng, title: distanceString, icon: bxmarker, map: map }); read more..

  • Page - 217

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 204 Subject: <input type="text" name="subject" size="100" /> <p> Body of message (you may change it) <br/> <TEXTAREA NAME="body" COLS=40 ROWS=5> My geolocation is at the address given in the subject line. </TEXTAREA> read more..

  • Page - 218

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 205 Another feature of PHP, which probably is the strangest to experienced programmers, is that variables can be included in strings. The statement echo("There was a problem: <br>the body is $body,<br> the to is $to,<br> subject is $subject,<br> headers is $headers."); produces read more..

  • Page - 219

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 206 Table 6-1. Functions in the Basic Geolocation Project Function Invoked/Called By Calls init Invoked by action of the onLoad attribute in the <body> tag handler Invoked by action of the getCurrentPosition call in init makemap, reversegeo reversegeo Invoked in handler read more..

  • Page - 220

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 207 Code Line Description </style> Closing tag for style <script type="text/javascript" charset="UTF-8" src="http://maps.google.com/maps/api/js?sensor=false"></script> Script to bring in Google Map API <script type="text/javascript" charset="UTF-8"> Opening script read more..

  • Page - 221

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 208 Code Line Description navigator.geolocation.getCurrentPosition(handler, problemhandler, positionopts); If so, make the call with parameters as shown } Close clause else { Else if (document.getElementById("place")) { If there is a place with ID place read more..

  • Page - 222

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 209 Code Line Description document.coutput.lon.value = mylong; Display the longitude document.coutput.acc.value = position.coords.accuracy; Display the accuracy reversegeo(blatlng); Invoke (my) function reversegeo } Close handler read more..

  • Page - 223

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 210 Code Line Description }); Close function definition, close Geocode method call } Close reversegeo function function problemhandler(prob) { Header for problemhandler function; prob will have information on the failure switch(prob.code) { switch statement based read more..

  • Page - 224

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 211 Code Line Description } Close problemhandler function var rxmarker = "rx1.png"; Red x; used for the base var bxmarker = "bx1.png"; Black x; used for clicks function makemap(mylat,mylong) { Header for makemap function var marker; Will hold marker read more..

  • Page - 225

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 212 Code Line Description map: map }); Marker is on map; close Marker method call listener = google.maps.event.addListener(map, 'click', function(event) { Set up event handling for clicking the map; function is defined here read more..

  • Page - 226

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 213 Code Line Description } Close checkit function function dist(point1, point2) { Header for distance between two points var R = 6371; // km Factor for kilometers // var R = 3959; // miles Factor for miles; keep in code just in read more..

  • Page - 227

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 214 Code Line Description </form> Closing form tag Last address <div id="address"></div> Div for addresses Distance <div id="distance"></div> Div for distances </body> Closing body tag </html> Closing html tag You can build on the basic read more..

  • Page - 228

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 215 Table 6-3. Functions in the E-mail Geolocation Project (Same As the Basic Geolocation Project) Function Invoked/Called By Calls init Invoked by action of the onLoad attribute in the <body> tag handler Invoked by action of the getCurrentPosition call in init read more..

  • Page - 229

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 216 Code Line Description <script type="text/javascript" charset="UTF-8" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript" charset="UTF-8"> var positionopts; positionopts = { enableHighAccuracy: true, read more..

  • Page - 230

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 217 Code Line Description } var listener; var map; var blatlng; var myOptions; function handler(position) { var mylat = position.coords.latitude; var mylong = position.coords.longitude; var result; read more..

  • Page - 231

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 218 Code Line Description } else { alert("No results found in reverse geocoding."); } } else { alert("Geocoder failed due to: " + status); } }); } function read more..

  • Page - 232

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 219 Code Line Description document.getElementById("header").innerHTML = "Base location needs to be set!"; } var xmarker = "x1.png"; function makemap(mylat,mylong) { var marker; blatlng = new google.maps.LatLng(mylat,mylong); read more..

  • Page - 233

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 220 Code Line Description } function checkit(clatlng) { var distance = dist(clatlng,blatlng); var result; distance = Math.floor((distance+.005)*100)/100; var distanceString = String(distance)+" km. away."; read more..

  • Page - 234

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 221 Code Line Description var lon2 = point2.lng()*Math.PI/180; var d = Math.acos(Math.sin(lat1)*Math.sin(lat2) + Math.cos(lat1)*Math.cos(lat2) * Math.cos(lon2-lon1)) * R; return d; } </script> </head> <body onLoad="init();"> <header read more..

  • Page - 235

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 222 Code Line Description To email Label for the To input field <input type="email" name="to" required /> This field is required and is of type email </p> Force a line break Subject: <input type="text" name="subject" size="100" /> read more..

  • Page - 236

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 223 Table 6-5. Code for the PHP Script for Sending E-mail Code Line Description <?php Delimiter for PHP code $to = $_POST['to']; Set the variable $to to the value of the form input with name to $subject = $_POST['subject']; Set the read more..

  • Page - 237

    CHAPTER 6 ■ WHERE AM I: USING GEOLOCATION, THE GOOGLE MAPS API, AND PHP 224 computer. To test the e-mail application, you need to run the program from your server. That is, you need to upload all the files to the server. My files are geolocationkmemail.html, rx1.png, and sendemailp.php. Moreover, I’ll repeat what I mentioned earlier: you need to check that read more..

  • Page - 238

    C H A P T E R 7 225 Origami Directions: Using Math-Based Line Drawings, Photographs, and Videos In this chapter, you will learn the following: • How to use mathematics to write JavaScript functions to produce precise line drawings • A methodology for combining line drawings, photographs, and videos, along with text read more..

  • Page - 239

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 226 Figure 7-1 shows the opening screen of the Talking Fish application, origamifish.html. The screen shows the standard conventions for origami diagrams, modified by me to include color. The standard origami paper, called kami, is white on one side and a nonwhite color on the read more..

  • Page - 240

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 227 Figure 7-2. First step, showing the square of paper. The instructions say to turn the paper. Skipping ahead, Figure 7-3 shows a later step in the folding. Notice that the colored side of the paper is showing. An unfolded fold line is indicated by the skinny read more..

  • Page - 241

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 228 Figure 7-3. Folding a corner down to a fold line Later in the construction of the model, the folder must perform a sink fold. This is considered a difficult move. Figure 7-4 shows what is called the crease pattern prior to the sink: the folds are indicated as mountain folds or read more..

  • Page - 242

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 229 I decided to supplement the line drawing with a video clip showing the sink step. Figure 7-5 shows a frame from the video. I (the folder) have used the video controls to pause the action. The folder can replay the video clip and go back to the crease pattern read more..

  • Page - 243

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 230 Figure 7-6. Step after sink (first video clip) The next step requires the folder to fold the triangular flap on the right backward, dividing the angle. Notice that the angle is indicated by an arc. Moving on again in the folding, there is a step for read more..

  • Page - 244

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 231 Figure 7-8 shows the result of moving the folded material to one side, as instructed in the directions shown in Figure 7-7. Figure 7-8. Photograph of the fish with the throat fixed The directions end with another video clip, this one showing the fish talking, read more..

  • Page - 245

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 232 Figure 7-9. Video showing talking fish Critical Requirements There is a standard format for origami directions, commonly referred to as diagrams, and I built on that standard. In this approach, each step shows the next fold to be made using a set typography. read more..

  • Page - 246

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 233 Steps for origami typically come with text instructions. Also, arrows are sometimes used. I wanted to follow the standard while still taking advantage of the fact that these instructions would be delivered on a computer, with color and the opportunity for other media. read more..

  • Page - 247

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 234 [oneflapup,"Do the same thing to the flap on the left"], [bothflapsup,"Make fins by wrapping top of right flap around 1 layer and left around back layer"], [finsp,"Now make lips...make preparation folds"], [preparelips,"and turn lips read more..

  • Page - 248

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 235 clears the canvas and resets the linewidth. The donext function then presents the nextstep step. The display includes parts: a graphic part consisting of a line drawing, video or image and a text part consisting of the instructions. The donext function invokesg read more..

  • Page - 249

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 236 <hr/> <button onClick="goback();" style="color: #F00">Go back </button> <button onClick="donext();" style="color: #03F">Next step </button> The color designations, each only three characters, are the equivalent of #FF0000 and #0033FF. These two sections read more..

  • Page - 250

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 237 The variable names kamiw and kamih refer to the width and height of the standard square paper for origami. From now on, everything is calculated. The first value required is the size of the diagonal of the paper. For a square, using the Pythagorean theorem, the read more..

  • Page - 251

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 238 The valley function determines how many dashes there will be. This is done by dividing the length of the valley line by the total length of a dash and the gap between dashes. If this is not a whole number, the last-and-partial-dash-gap combination is dropped. The Math.floor method read more..

  • Page - 252

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 239 ctx.closePath(); ctx.stroke(); ctx.lineWidth = origwidth; } At one point for the directions for the origami fish, I decided to use short, downward-pointing arrows. I wrote a general function for it, which you can study in the commented code in the read more..

  • Page - 253

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 240 The next step is to set these two expressions equal to each other and solve for x. What this accomplishes is calculating a value for x that lies on both lines. With that value of x, I use one of the two equations to get the corresponding y. The pair x,y read more..

  • Page - 254

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 241 Figure 7-11. Dividing-into-thirds step ■ Note My instructions do not suggest ways to do this. A common way that folders do this is to make a guess for the point one-third of the way from one end—say, the left. Fold the right point to that point and make a read more..

  • Page - 255

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 242 The variables defining the four points are var e = proportion(ax,ay,cx,cy,.333333); var ex = e[0]; var ey = e[1]; var f = proportion(ax,ay,cx,cy,.666666); var fx = f[0]; var fy = f[1]; var g = proportion(ax,ay,dx,dy,.666666); var gx = g[0]; var gy = g[1]; The function triangleM read more..

  • Page - 256

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 243 Also, do not assume that I knew to write this function. I probably put this coding into the first function and then when I got to the next step of the model, realized that I needed a triangle again. I extracted the code I had written and renamed the read more..

  • Page - 257

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 244 var kx = ax+diag/3; var ky = ay; var lx = kx + diag/3; var ly = ay; var mx = ax + diag/6; var innersq = Math.sqrt(2)*diag/6; var my = ay + innersq*Math.sin(Math.PI/4); var nx = ax+diag/3+diag/6; var ny = my; var px = mx; var py = dy; var rx = nx; var ry = py; read more..

  • Page - 258

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 245 Figure 7-15. Labeling at fold in half step Figure 7-16. Preparing to sink center read more..

  • Page - 259

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 246 Figure 7-17. After wraparound steps Figure 7-18. After making lips Use the figures to help understand the code setting the values of variables. For example, as I mentioned in describing the intersect function, looking at 0s 7-14 and 7-17, you can see that read more..

  • Page - 260

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 247 function rotatefish() { ctx.save(); ctx.translate(kx,my); ctx.rotate(-Math.PI/2); ctx.translate(-kx,-my); lips(); ctx.restore(); } Displaying a Photograph The steps that display a photograph in have the same structure as the ones producing a line read more..

  • Page - 261

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 248 Building the Application and Making It Your Own The quickest way to build on what you have learned in this chapter is to create directions for another craft project similar to paper folding in the presence of line drawings and the benefits of some photographs and video clips. You read more..

  • Page - 262

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 249 Table 7-2 shows the code for the basic application, with comments for each line. Much of this code you have seen in previous chapters. Table 7-2. Insert Table Caption Code Line Description <!DOCTYPE html> Header <html> html tag <head> Head tag read more..

  • Page - 263

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 250 Code Line Description var dashlen = 8; Set length of dash in valley fold var dgap = 2.0; Set gap between dashes var ddashlen = 6.0; Set dash length in mountain fold var ddot = 2.0; Set dot length in mountain fold var dratio = dashlen/(dashlen+dgap); Used for mountain read more..

  • Page - 264

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 251 Code Line Description // are not vertical . . . and assumes lines aren’t vertical; if they were, the code would be dividing by zero, which would produce an error var m12 = (y2-y1)/(x2-x1); Compute slope var m34 = (y4-y3)/(x4-x3); Compute slope read more..

  • Page - 265

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 252 Code Line Description } Close init function function directions() { Header for directions, the first ‘’“step” shown ctx.fillStyle = "black"; Change fill style, for use in text ctx.font = "15px Georgia, Times, serif"; Set font read more..

  • Page - 266

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 253 Code Line Description if (v) { Check if v is set v.pause(); Pause the video v.style.display = "none"; Make it not display v = undefined; Set v to undefined canvas1.height = 480; read more..

  • Page - 267

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 254 Code Line Description ctx.moveTo(x,y-20) Move to right above the (x,y) position ctx.lineTo(x,y-7); Draw line to just above the (x,y) ctx.moveTo(x-5,y-12); Move to the left and up ctx.lineTo(x,y-7); Draw diagonal line ctx.moveTo(x+5,y-12); Move to read more..

  • Page - 268

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 255 Code Line Description ctx.closePath(); Close path ctx.stroke(); Make stroke ctx.lineWidth = origwidth; Reset line width } Close skinnyline var origstyle; Will hold original color var origwidth = 2; Set to line width for most lines function read more..

  • Page - 269

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 256 Code Line Description ctx.stroke(); Draw the path ctx.strokeStyle = origstyle; Reset stroke style } Close valley function function mountain(x1,y1,x2,y2,color) { Header for mountain function var px=x2-x1; Set difference in x var py = y2-y1; Set difference read more..

  • Page - 270

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 257 Code Line Description ctx.stroke(); Draw the path ctx.strokeStyle = origstyle; Reset stroke style } Close mountain function function curvedarrow(x1,y1,x2,y2,px,py){ Header for curvedarrow from (x1,y1) to (x2,y2) offset by (px,py) var arrowanglestart; Start Angle read more..

  • Page - 271

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 258 Code Line Description ctrx = .5*(x1+x2) +px; Calculate center x ctry = y1+2*d +py; Calculate center y if (x1<x2) { For arrows going left to right ctx.arc(ctrx,ctry, rad,arrowanglestart,arrowanglefinish, false); Draw arc read more..

  • Page - 272

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 259 Code Line Description } End clause ctx.stroke(); Do the drawing for either case } End horizontal case else if (x1==x2) { Vertical line arrowanglestart = -angdel; Set starting angle arrowanglefinish = angdel; Set finishing angle ctrx = x1-2*d+px; read more..

  • Page - 273

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 260 Code Line Description ex = ctrx+rad*Math.cos(fromhorizontal); Calculate x for little lines ey = ctry - rad*Math.sin(fromhorizontal); Calculate y for little lines ctx.lineTo(ex-8,ey+8); Draw first little line ctx.moveTo(ex,ey); Move to end of second line ctx.lineTo(ex+8,ey+8); Draw read more..

  • Page - 274

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 261 Code Line Description folds as indicated ..."], [changedfolds,"note middle square sides all valley folds, some other folds changed. Flip over."], [precollapse,"Push sides to sink middle square."], [playsink,"Sink square, collapse model."], read more..

  • Page - 275

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 262 Code Line Description var ay = 220; Set y for left corner var bx = ax+ .5*diag; Calculate b (top corner) var by = ay - .5*diag; var cx = ax + diag; Calculate c (right) var cy = ay; var dx = bx; Calculate d (bottom) var dy = ay + .5*diag; var e = read more..

  • Page - 276

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 263 Code Line Description var gry = ay-(gy-ay); var kx = ax+diag/3; See Figure 7-14 for k through s var ky = ay; var lx = kx + diag/3; var ly = ay; var mx = ax + diag/6; var innersq = Math.sqrt(2)*diag/6; var my = ay + innersq*Math.sin(Math.PI/4); var read more..

  • Page - 277

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 264 Code Line Description var xxa = intersect(sx,sy,qx,qy,kx,ky,nx,ny); var xxx = xxa[0]; var xxy = xxa[1]; var xxlx = kx-(xxx-kx); var xxly = xxy; var slx = kx- (sx-kx); var sly = sy; var tlx = tx-5; var tly = ty; var dkt=ky-ty; var finlx = kx-dkt; See read more..

  • Page - 278

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 265 Code Line Description var rlipy = ry-10; var plipex = px - 10; var plipey = plipy; var rlipex = rx + 10; var rlipey = rlipy; var rclipcleft1 = proportion(rlipex,rlipey,rlipx,rlipy,.5); var pclipcleft1 = proportion(plipex,plipey,plipx,plipy,.5); var rclipcleft2 = read more..

  • Page - 279

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 266 Code Line Description throat2.src = "throat2.jpg" Set src var cleft = new Image(); Define Image object cleft.src="cleftlip.jpg"; Set src function showcleftlip() { Header for showcleftlip ctx.drawImage(cleft,40,40); Draw image } close showcleftlip function read more..

  • Page - 280

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 267 Code Line Description v.currentTime = 0; Set at start v.play(); Play canvas1.height = 178; Adjusts for height of video } Close playsink function lips() { Header for lips ctx.fillStyle = "teal"; Set color ctx.beginPath(); read more..

  • Page - 281

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 268 Code Line Description ctx.lineTo(nx,ny); Draw right and down ctx.lineTo(rlipx,rlipy); Draw down to rlip ctx.lineTo(qx,qy); Draw to center q ctx.lineTo(xxx,xxy); Draw back to xx ctx.closePath(); Close path ctx.fill(); Fill in shape ctx.stroke(); read more..

  • Page - 282

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 269 Code Line Description skinnyline(kx,ky,qx,qy); Draw vertical center line ctx.fillStyle="teal"; Reset to color } Close lips function rotatefish() { Header for rotatefish ctx.save(); Save current coordinate system ctx.translate(kx,my); Move to a read more..

  • Page - 283

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 270 Code Line Description } Close finsp function fins() { Header for fins ctx.beginPath(); Begin path ctx.moveTo(finlx,finly); Move to left fin ctx.lineTo(kx,ky); Draw line to center ctx.lineTo(wx,wy); Draw line left and down ctx.lineTo(finlx,finly); Draw read more..

  • Page - 284

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 271 Code Line Description ctx.closePath(); Close path ctx.fill(); Fill in shape ctx.stroke(); Draw outline skinnyline(kx,ky,qx,qy); Draw skinny line indicated center fold } Close fins function bothflapsup () { Header for bothflapsup read more..

  • Page - 285

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 272 Code Line Description ctx.lineTo(tx,ty); Draw up ctx.moveTo(xxx,xxy); Draw to right ctx.lineTo(nx,ny); Draw to right ctx.lineTo(rx,ry); Draw down to tip ctx.lineTo(qx,qy); Draw to center ctx.lineTo(xxx,xxy); Draw back to right ctx.closePath(); read more..

  • Page - 286

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 273 Code Line Description ctx.lineTo(mx,my); Draw up ctx.lineTo(kx,ky); Draw (back to) middle top ctx.moveTo(xxx,xxy); Draw right, down ctx.lineTo(nx,ny); Draw down ctx.lineTo(rx,ry); Draw down to right tip ctx.lineTo(qx,qy); Draw to center read more..

  • Page - 287

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 274 Code Line Description ctx.lineTo(ax,ay); Draw back to corner ctx.moveTo(kx,ky); Move to center ctx.lineTo(lx,ly); Draw to right corner ctx.lineTo(px,py); Draw down and left ctx.lineTo(mx,my); Draw up ctx.lineTo(kx,ky); Draw back to center read more..

  • Page - 288

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 275 Code Line Description valley(ax,ay,cx,cy); Indicate valley across paper valley(ex,ey,gx,gy); Indicate valley, midway and down on left valley(fx,fy,hx,hy); Indicate valley, midway and down on right mountain(ex,ey,gx,gry); Indicate mountain, midway and up on left read more..

  • Page - 289

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 276 Code Line Description valley(fx,fy,hx,gry); Valley center, up on right valley(jx,jy-diag6,jx,jy+diag6); Valley in middle of paper, vertical mountain(jx,jy-diag6,bx,by); Mountain from inner diamond up mountain(jx,jy+diag6,dx,dy); Mountain from inner diamond down read more..

  • Page - 290

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 277 Code Line Description valley(jx,jy+diag6,dx,dy); valley, inner diamond down valley(ex,ey,jx,jy+diag6); Valley, top, left side of inner diamond valley(jx,jy-diag6,fx,fy); Valley, top, right side of inner diamond valley(ex,ey,jx,jy-diag6); Valley, bottom, left side of read more..

  • Page - 291

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 278 Code Line Description function cornerdown() { Header for cornerdown rttriangle(); Draw right triangle ctx.clearRect(ex,ey, diag6+5,diag6); Erase rectangle covering corner ctx.beginPath(); Begin path ctx.moveTo(ex,ey); Move to start ctx.lineTo(ex+diag6,ey+diag6); Draw right read more..

  • Page - 292

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 279 Code Line Description ctx.moveTo(ax,ay); Move to left corner ctx.lineTo(bx,by); Line up and right ctx.lineTo(cx,cy); Line down and right ctx.lineTo(dx,dy); Line down and to middle ctx.lineTo(ax,ay) Line to start ctx.closePath(); Close path read more..

  • Page - 293

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 280 Code Line Description ctx.beginPath(); Begin path ctx.moveTo(ax,ay); Move to left corner ctx.lineTo(cx,cy); Draw line across ctx.lineTo(dx,dy); Draw line down ctx.lineTo(ax,ay); Draw line back up ctx.closePath(); Close path ctx.fill(); Fill in shape } Close read more..

  • Page - 294

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 281 Code Line Description <body onLoad="init();"> Body, with call to init <video id="sink" loop="loop" preload="auto" controls="controls" width="400"> Video tag <source src="sink.mp4video.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> read more..

  • Page - 295

    CHAPTER 7 ■ ORIGAMI DIRECTIONS: USING MATH-BASED LINE DRAWINGS, PHOT0GRAPHS, AND VIDEOS 282 Code Line Description <hr/> Horizontal rule <button onClick="goback();" style="color: #F00">Go back </button> Set up “Go back” button <button onClick="donext();" style="color: #03F">Next step </button> Set up “Next step” button </body> read more..

  • Page - 296

    C H A P T E R 8 283 Jigsaw Video: Using the Mouse and Touch to Arrange Images In this chapter, you will learn the following: • How to set up mouse and touch events to build an application to work on a variety of devices • Ways to break up a picture into pieces and determine the read more..

  • Page - 297

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 284 Figure 8-1. Opening screen on computer On a computer, the player uses the mouse to move and reposition pieces. Randomly positioned pieces may end up on top of each other. Figure 8-2 shows the jigsaw pieces spread out. I did this using the mouse. My example has six read more..

  • Page - 298

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 285 Figure 8-2. Pieces spread out Figure 8-3 shows how I have made progress in putting the puzzle together. I can position the puzzle anywhere on the screen. Three pieces of the puzzle have been put together. read more..

  • Page - 299

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 286 Figure 8-3. Progress made on the puzzle Notice that the box with the label Feedback says to keep working. Figure 8-4 shows the puzzle nearly complete. read more..

  • Page - 300

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 287 Figure 8-4. Just one piece left to fit into the jigsaw puzzle The program allows for a margin of error, which I term the tolerance, when putting the pieces together. You can see by noticing the white border along the dance floor that the puzzle is not perfectly put read more..

  • Page - 301

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 288 Figure 8-5. Pieces replaced by a video Notice that the feedback now reads “GOOD!” A video has begun to play. The picture appears perfect. In fact, the six jigsaw pieces have been replaced by the video. Figure 8-6 shows the video with controls showing. The controls do not show automatically, read more..

  • Page - 302

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 289 Figure 8-6. Video clip with controls I decided to attempt the task of making the project work for an iPhone and iPad. This meant constructing a user interface that allows the player to use finger touches. To be more ambitious, I wanted to produce one program read more..

  • Page - 303

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 290 Figure 8-7. Opening screen on an iPhone Notice that you and the player cannot see the bottom part of the original screen with the “Do jigsaw again” button and the feedback. I decided to accept this in order to avoid squeezing the playing area or reducing the size read more..

  • Page - 304

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 291 Figure 8-8. Jigsaw game in progress on an iPhone Figure 8-9 shows the screen immediately following successful completion of the puzzle. read more..

  • Page - 305

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 292 Figure 8-9. Video ready to play on an iPhone The iPhone operating system requires users to click the play button for all videos. This is considered a feature, not a bug, by the makers of the iPhone. Requiring a click does give the owner of the iPhone a chance to read more..

  • Page - 306

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 293 Figure 8-10. Video in play on an iPhone With this introduction to what can be called the jigsaw-puzzle-with-video-reward project, we can go on to discuss the requirements for the project and the implementation. Background and Critical Requirements Three distinct circumstances read more..

  • Page - 307

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 294 The requirements for this project start with acquiring the images that will be the jigsaw pieces using as a base the first frame of a video clip. Next, since it will be necessary to determine if the jigsaw is complete—that is, if the pieces have been read more..

  • Page - 308

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 295 Figure 8-11. Screenshot from Corel Paint Shop Pro At the bottom of Figure 8-11, the (77,72) indicates the location of the top-left corner of the picture relative to the original picture. I recorded these values for each individual jigsaw puzzle piece. These values are what read more..

  • Page - 309

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 296 game, in which the jigsaw puzzle was just a part. However, breaking up a function into smaller pieces generally is a good thing to do. The init function does some work, calls setupgame, and also calls setupjigsaw. The setupjigsaw function is also invoked from endjigsaw. More read more..

  • Page - 310

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 297 Setting Up the Jigsaw Puzzle The work of setting up the jigsaw puzzle starts with stopping the video and making it not display. This isn’t necessary the very first time, but it is easier to have the code always perform these operations. The next task is to place read more..

  • Page - 311

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 298 ■ Note The event handling in this program does not make use of the new drag-and-drop features of HTML5. These features are intended for use when you need to write code that moves elements from one bin-like element into or onto another. The read more..

  • Page - 312

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 299 it is not necessarily the one on top, but the one first in the pieceelements array. This is probably an opportunity for improvement, to put it in a noncritical light. for (i=0; i<nums;i++) { j = pieceelements[i]; o = offset(j); read more..

  • Page - 313

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 300 The dot in the piece at the right middle represents where the player has moved the mouse and pressed down on the button. (The dot does not appear during the game; I put it in the figure for reference.) The bottom arrow represents curX, the distance from the left side read more..

  • Page - 314

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 301 else draw(e.pageX, e.pageY); } The draw function does the work: repositioning the movingobj element: function draw(x, y) { var js = movingobj.style; js.left = (x - adjustX) + "px"; js.top = (y - adjustY) + "px"; } The draw read more..

  • Page - 315

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 302 Using Finger Touches It is time to explain how touch events can be made to mimic mouse events. The basic touch events are defined as follows by the W3C (see www.w3.org/TR/2011/WD-touch-events-20110505): • touchstart: This is triggered when a touch is initiated (mouse equivalent: read more..

  • Page - 316

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 303 var simulatedEvent = document.createEvent("MouseEvent"); simulatedEvent.initMouseEvent(type, true, true, window, 1, first.screenX, first.screenY, read more..

  • Page - 317

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 304 function doaverage(arr) { var sum; var i; var n = arr.length; sum = 0; for(i=0;i<n;i++) { sum += arr[i]; } return (sum/n); } The first part of checkpositions follows: function checkpositions() { var i; var x; read more..

  • Page - 318

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 305 Preparing, Positioning, and Playing the Video and Making It Hidden or Visible Preparing the video clip is the same as what you have seen for the other projects involving video. You need to create multiple encodings of the video. Also, as with the other projects, when we read more..

  • Page - 319

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 306 • checkpositions: For determining if the puzzle is complete • offset: For calculating the position of pieces in motion • draw: For actually doing the repositioning of pieces • doaverage: For calculating the average of values in an array Table 8-1 lists all the read more..

  • Page - 320

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 307 Table 8-2. Complete Code for the Jigsaw-to-Video Project Code Line Description <!DOCTYPE html> Header <html> html tag <head> Head tag <title>Jigsaw</title> Complete title element <meta name="viewport" content="width=device- width, user-scalable=yes, read more..

  • Page - 321

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 308 Code Line Description </style> Closing style tag <script type="text/javascript"> Script tag var pieces = ["dan1.jpg","dan2.jpg","dan3.jpg","dan4.jpg", "dan5.jpg","dan6.jpg" ]; Hold names of image files for pieces var piecesx=[0,71, 124,0,77,123]; Hold x read more..

  • Page - 322

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 309 Code Line Description function setupgame() { Header for setupgame var i; For indexing over pieces var x; For x value var y; For y value var uniqueid; Generated, unique ID for the puzzle pieces var s; Reference created element read more..

  • Page - 323

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 310 Code Line Description questionfel = document.getElementById("questionform"); Set reference to form questionfel.style.left = "20px"; Position form horizontally questionfel.style.top = "400px"; Position form vertically questionfel.feedback.value = " "; Set feedback to zero read more..

  • Page - 324

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 311 Code Line Description var i; For indexing var x; For x value var y; For y value var tolerance = 10; Set tolerance for puzzle var deltax = []; Will hold all x differences var deltay = []; Will hold all y differences var read more..

  • Page - 325

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 312 Code Line Description for (i=0;i<nums;i++) { Iterate over pieces (again) if ((Math.abs(averagex - deltax[i])>tolerance) || (Math.abs(averagey- deltay[i])>tolerance)) { Are any of the delta values too different from the average? break; If so, leave for read more..

  • Page - 326

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 313 Code Line Description } Close checkpositions function function doaverage(arr) { Header for doaverage function var sum; Will hold sum var i; For indexing var n = arr.length; The length of the array sum = 0; Initialize sum to zero read more..

  • Page - 327

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 314 Code Line Description thingelem = pieceelements[i]; Extract ith element thingelem.style.top = String(y)+"px"; Set its top attribute thingelem.style.left = String(x)+"px"; Set its left attribute thingelem.style.display = "inline"; Set display to visible (inline means no line read more..

  • Page - 328

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 315 Code Line Description function touchHandler(event) { Header for touchHandler var touches = event.changedTouches; Extract all the touches if (touches.length>1) { If there is more than one return false; } Exit function var first = touches[0]; Extract the read more..

  • Page - 329

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 316 Code Line Description var ie= d.all; Flag for certain browsers, namely Internet Explorer var mouseDown = false; Initialize mouseDown to false var adjustX; For horizontal adjust value var adjustY; For vertical adjust value var movingobj; Will hold the moving element function release(e){ read more..

  • Page - 330

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 317 Code Line Description { Start clause break; Leave for loop } Close clause } Close for loop if (i<nums) { Did for loop break early? movingobj = pieceelements[i]; . . . set read more..

  • Page - 331

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 318 Code Line Description js.top = (y - adjustY) + "px"; Set the top to the calculated value, concatenate the px } Close draw function function offset(obj) { Header for offset calculation var left = 0; Set initial left var top = 0; Set initial top if read more..

  • Page - 332

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 319 Code Line Description </form> Closing form tag <video id="dance" loop="loop" preload="auto" controls="controls" autoplay> Video tag <source src="dance.webm" type='video/webm; codec="vp8, vorbis"'> Source <source src="dance.mp4"> Source <source read more..

  • Page - 333

    CHAPTER 8 ■ JIGSAW VIDEO: USING THE MOUSE AND TOUCH TO ARRANGE IMAGES 320 • Determining the coordinate values that indicated how the pieces fit together and using those values, along with a defined tolerance, to check if the jigsaw puzzle was put together adequately • When appropriate, making the video appear and play In the next chapter, we read more..

  • Page - 334

    C H A P T E R 9 321 US States Game: Building a Multiactivity Game In this chapter, you will learn the following: • How to build a user interface for a game involving different types of player moves, including putting together a jigsaw puzzle • How to use the mouse to reposition pieces • How to read more..

  • Page - 335

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 322 Figure 9-1. Opening screen of the US states game I followed the common practice and present a map with Alaska and Hawaii not in correct position nor proportionally sized. Note also that Rhode Island is bigger than it really is so there’s enough room to click it. read more..

  • Page - 336

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 323 Figure 9-2. The prompt is to find Washington. When I clicked Oregon, I saw what is shown in Figure 9-3. Figure 9-3. Response to an incorrect choice read more..

  • Page - 337

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 324 When I clicked the correct choice, the application responded appropriately, as shown in Figure 9-4. Figure 9-4. Response to a correct answer I decided that it would be helpful to offer the player the option to spread out all the states. After clicking the button labeled read more..

  • Page - 338

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 325 The player can use the “Restore original/compress map” button or keep playing with the states spread out. Clicking the “Name the state” button produces a prompt consisting of one randomly selected state surrounded by a border, as shown in Figure 9-6. Figure 9-6. Border around read more..

  • Page - 339

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 326 Figure 9-7. Response after the correct answer is submitted The application also provides activity for the player in the form of a jigsaw puzzle. After clicking the “Do jigsaw” button, you will see something like Figure 9-8. I say “something like” because the states are read more..

  • Page - 340

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 327 The player can now use the mouse to drag and drop pieces in the same manner (and implemented the same way) as the jigsaw-to-video puzzle described in Chapter 8. Figure 9-9 shows my work in progress. Figure 9-9. Jigsaw puzzle in progress Observe that I have sorted out read more..

  • Page - 341

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 328 Figure 9-10. Not quite correct The feedback indicates that something is wrong with North Dakota. After cheating—that is, clicking “Save & cl ose jigsaw” and looking at the completed map—I realized that North Dakota and Kansas, two similar ectangular shapes, needed to be swapped. Figure 9-11 shows the read more..

  • Page - 342

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 329 Notice that the positions of Alaska and Hawaii are not closely examined. The puzzle is deemed complete. After this introduction showing the features of this educational game, I will describe the critical requirements for implementation. Critical Requirements The critical requirements for read more..

  • Page - 343

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 330 The first tasks for making the individual pieces representing the states are to acquire a map of the United States (or the country or region you pick), and then produce an image file for each state. The web-based pixlr image-editing tool (http://pixlr.com/), Corel Paint Shop Pro, and other read more..

  • Page - 344

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 331 Figure 9-13. Map of the United States, with the magic wand on Illinois After clicking the light-green area representing Illinois, Illinois, and only Illinois, becomes selected, as shown in Figure 9-14. I will be copying and pasting this to save as its own image, but I need to read more..

  • Page - 345

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 332 The next step is to determine the relative position of each piece representing a state in terms of a base point. I demonstrated this in Chapter 8 for rectangular shapes. We have the same task here, but the shapes are, for the most part, not rectangles. One choice for a base read more..

  • Page - 346

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 333 Figure 9-16. Illinois moved to its new origin Notice that the crosshair (+) is now at the upper-left corner. For comparison, Figure 9-17 shows the original symbol for Hawaii and Figure 9-18 shows the adjusted image. Figure 9-17. Hawaii symbol read more..

  • Page - 347

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 334 Figure 9-18. Hawaii with adjusted origin If you decide to use Flash, you must use the File  Export  Export Image facility to produce an image file (see Figure 9-19). Figure 9-19. Exporting an image in Adobe Flash read more..

  • Page - 348

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 335 If you use another image-processing program, you save the images in the standard manner as GIFs or PNGs. You do want the images to have transparent backgrounds, so this may mean more work in an image-processing program to achieve this. The image elements in HTML are rectangular, so read more..

  • Page - 349

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 336 questionfel = document.getElementById("questionform"); questionfel.style.left = "100px"; questionfel.style.top = "500px"; questionfel.question.value = " "; questionfel.feedback.value = " "; } The element is created of a custom defined type 'state'. read more..

  • Page - 350

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 337 The setupfindstate function makes a random choice among the states. The global variable choice holds value made for the random choice. The function then sets up event handling for each of the elements corresponding to a state. The prompt for the player is placed in read more..

  • Page - 351

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 338 function setupidentifystate(){ stateelements[choice].style.border=""; stateelements[choice].style.zIndex = ""; choice = Math.floor(Math.random()*nums); stateelements[choice].style.border="double"; stateelements[choice].style.zIndex = "20"; questionfel.question.value read more..

  • Page - 352

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 339 function spread() { var i; var x; var y; var thingelem; for (i=0;i<nums-2;i++) { // don't move alaska or hawaii x = 2.70*statesx[i] +410; y = 2.70*statesy[i] + 250; thingelem = stateelements[i]; read more..

  • Page - 353

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 340 for (i=0;i<nums;i++) { x = 100+Math.floor(Math.random()*600); y = 100+Math.floor(Math.random()*320); thingelem = stateelements[i]; thingelem.style.top = String(y)+"px"; thingelem.style.left = String(x)+"px"; read more..

  • Page - 354

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 341 When all 50 strings have been placed in the array, my code uses the join method to combine everything in one big array, with the delimiter of my choice (;) separating them. This is the string that is stored using localStorage. In HTML5, localStorage is a variation on read more..

  • Page - 355

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 342 function restore() { var i; var x; var y; var thingelem; var df; var lsname = "jigsaw"; var xydata = []; var stringdata; if (doingjigsaw) { doingjigsaw = false; d.onmousedown = ""; read more..

  • Page - 356

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 343 stringdata = localStorage.getItem(lsname); xydata = stringdata.split(";"); for (i=0;i<nums;i++) { ss = xydata[i]; ssarray = ss.split("&"); thingelem = stateelements[i]; thingelem.style.top = ssarray[0]; thingelem.style.left = read more..

  • Page - 357

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 344 • setupidentifystate sets up the typing in the name, and checkname checks the response. • setupjigsaw sets up the jigsaw puzzle. The functions startdragging, moving, and release, along with offset and draw, handle the player actions with regard to using the mouse to move pieces. The read more..

  • Page - 358

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 345 Function Invoked/Called By Calls release Invoked by setting up events in restorepreviousjigsaw and setupjigsaw checkpositions startdragging Invoked by setting up events in restorepreviousjigsaw and setupjigsaw offset moving Invoked by setting up events in restorepreviousjigsaw and setupjigsaw draw read more..

  • Page - 359

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 346 Code Line Description <script type="text/javascript"> Script tag var names = [ Names of the states; one of many parallel arrays with information on states; order and grouping here not important but order must be the same and Alaska and Hawaii last read more..

  • Page - 360

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 347 Code Line Description "missouri.gif", "oregon.gif", "michigan.gif", "indiana.gif", "vermont.gif","newhampshire.gif","maine.gif","sou thdakota.gif","northdakota.gif", read more..

  • Page - 361

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 348 Code Line Description 88.65,60.15,65.40, -81.70,90.40, 107.40,171.95,181.00,183.00,21.10,22.60, 121.70,78.90,103.65,99.40, 132.20,138.95,125.45,110.45,93.90, 138.95,138.95,151.65,171.95,144.20,174.20,147.95, 187.75,179.35,177.60,77.40,73.65,54.15, 115.70,32.35, -44.95,-86.85,-8.15,-47.20,-32.15,21.10, read more..

  • Page - 362

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 349 Code Line Description 15.15,-35.75,-11.85,-76.70,-76.30,-23.85, -27.60,18.15,22.65,19.65,-22.35,-83.45,- 41.75,31.55,-171.30 ]; End of statesy array var doingjigsaw = false; Flag indicating if doing jigsaw function init(){ Header for init function setupgame(); Invoke setupgame read more..

  • Page - 363

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 350 Code Line Description s = document.createElement('state'); Create element s.innerHTML = ( "<img src='"+states[i]+ "' id='"+uniqueid+"'/>"); Set the HTML markup contents of the newly created element to be an image with the attributes as indicated document.body.appendChild(s); read more..

  • Page - 364

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 351 Code Line Description else { Else questionfel.feedback.value = "Try Again."; Display feedback to try again } Close clause } Close pickstate function function spread() { Header for spread function var i; For indexing var x; For x value var y; read more..

  • Page - 365

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 352 Code Line Description var df; Used to remove fullpage var lsname = "jigsaw"; Name for localStorage var xydata = []; Used for saving var stringdata; Used for saving if (doingjigsaw) { Check if doingjigsaw is true doingjigsaw = false; Set read more..

  • Page - 366

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 353 Code Line Description alert("data not saved, error given: "+e); Error message } Close catch clause } Close if doingjigsaw for (i=0;i<nums;i++) { Iterate over states x = statesx[i] +310; Set x to be original x-coordinate y = read more..

  • Page - 367

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 354 Code Line Description xydata = stringdata.split(";"); Generate an array from stringdata for (i=0;i<nums;i++) { Iterate over states ss = xydata[i]; Extract the ith element of xydata ssarray = ss.split("&"); Split this string to get two values read more..

  • Page - 368

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 355 Code Line Description catch(e) { Catch alert("Problem in restoring previous puzzle. Click on Do jigsaw.");} Display alert box } Close restorepreviousjigsaw function var choice = 0; Global variable holding right answer function setupfindstate(){ Header for setupfindstate read more..

  • Page - 369

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 356 Code Line Description stateelements[choice].style.zIndex=""; Put this state underneath what will be the next choice choice = Math.floor(Math.random()*nums); Make random choice stateelements[choice].style.border="double"; Set border around the choice state read more..

  • Page - 370

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 357 Code Line Description var guessedname = document.questionform.question.value; This was what the player typed in if (guessedname==correctname) { Was the player correct? questionfel.feedback.value = "Correct!"; Display feedback } End clause else { Else read more..

  • Page - 371

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 358 Code Line Description y = stateelements[i].style.top; Y is this state’s top x = x.substr(0,x.length-2); Remove px y = y.substr(0,y.length-2); Remove px x = Number(x); Convert to number y = Number(y); Convert to number delx = x - statesx[i]; read more..

  • Page - 372

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 359 Code Line Description else { Else loop did not end prematurely; could put in check on Hawaii and Alaska here questionfel.feedback.value = "GOOD"; Display feedback } Close clause } Close checkpositions function function doaverage(arr) { Header for doaverage function; parameter is read more..

  • Page - 373

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 360 Code Line Description for (i=0;i<nums;i++) { Iterate over states x = 100+Math.floor(Math.random()*600); Choose random value for x y = 100+Math.floor(Math.random()*320); Choose random value for y thingelem = stateelements[i]; Set ith element read more..

  • Page - 374

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 361 Code Line Description var ie= d.all; The Internet Explorer check; note that application has not been checked for latest Internet Explorer version var mouseDown = false; Initialize flag to false var curX; Current x var curY; Current y var adjustX; Used for dragging var adjustY; Used for read more..

  • Page - 375

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 362 Code Line Description if (curX >= o.x && curX <= o.x + j.width && curY >= o.y && curY <= o.y + j.height) Check if mouse over the ith element { break; } If so, leave for loop } End of clause if (i<nums) { Was for loop exited read more..

  • Page - 376

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 363 Code Line Description } Close draw function function offset(obj) { Header for offset function; adds in all offsets of obj from ancestors var left = 0; Initialize left var top = 0; Initialize top if (obj.offsetParent) Is there a parent? do { Then read more..

  • Page - 377

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 364 Code Line Description <button onClick="restorepreviousjigsaw();">Restore last jigsaw in process </button> Button to restore saved jigsaw <h1>USA</h1> heading on screen for the USA puzzle <form id="questionform" name="questionform" onSubmit="return checkname();"> Form tag, read more..

  • Page - 378

    CHAPTER 9 ■ US STATES GAME: BUILDING A MULTIACTIVITY GAME 365 • How to save and restore works-in-progress, including use of the try...catch construct. • Reuse of techniques explained in the last chapter: • Creating HTML markup dynamically to create the piece elements on the screen • Placing the jigsaw pieces randomly on the screen • read more..

  • Page - 379

    C H A P T E R 1 0 367 Web Site Database: Using PHP and MySQL In this chapter, you will do the following: • Receive an introduction to databases and Structured Query Language (SQL) • Learn how to create tables in a MySQL database • Learn how to use PHP to insert, update, delete, and select read more..

  • Page - 380

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 368 ■ Note I recognize that this is not as exciting as bouncing videos, talking fish, geographic portals to media, and jigsaw puzzles turning into video clips. Moreover, the application is just a little more than what is available to you through bookmarks on any browser. However, this application does serve read more..

  • Page - 381

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 369 Figure 10-3. Successful addition of finder (completereg.php) A characteristic of a database project is that attention needs to be paid to what can go wrong. For example, what if the person registering a new finder neglected to enter an e-mail address for the user ID? Figure 10-4 shows the response. Figure 10-4. read more..

  • Page - 382

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 370 Finders may change their passwords using the changepassword.html script. Figure 10-6 shows the opening screen. Figure 10-6. Opening screen for changing password (changepassword.html) Figure 10-7 shows data entered. The finder must know the current password, presumably given out by the system owner, to use read more..

  • Page - 383

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 371 Figure 10-9. Response to bad input for changing password I probably could have made this better—for example, by moving the “Passwords do not match” bubble closer to the input fields. One approach to doing this would be to use techniques such as shown in Chapter 4 for changing the read more..

  • Page - 384

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 372 Figure 10-11. Form filled in for adding a site (addsite.html) If the operation is successful, the finder is informed, and another similar form is presented, as shown in Figure 10-12. Figure 10-12. Feedback and chance to add another site or see sites (addsite.php) Notice that the password read more..

  • Page - 385

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 373 Figure 10-13. Display of all sites (showsites.php) If you clicked the “Show sites for a category” link or went directly to the showsitesbycategory1.php script, you would see something like what is shown in Figure 10-14. Figure 10-14. Screen for picking a category Clicking the read more..

  • Page - 386

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 374 Figure 10-17. Chance to delete (remove) sites (removesites.php) Note that any registered finder can delete any site. This may be something you want to change. Figure 10-18 shows how the screen would appear if someone clicked on two sites but neglected to log in. Figure 10-18. Reminder that read more..

  • Page - 387

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 375 Figure 10-20. Successful removal of two sites (completeremovesites.php) Recall that I specified that I wanted the username and password saved on my local computer when visiting the addsite script using the Firefox browser (see Figure 10-11). At some point, I closed Firefox. When I returned to read more..

  • Page - 388

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 376 When I click the downward arrow in the input field next to Date:, I see what is shown in Figure 10-23. Figure 10-23. Opera browser with date-picker calendar page (addsite.html) This completes the overview/introduction to the database application. In the next section, I will describe critical read more..

  • Page - 389

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 377 SQL, PHP, HTML5, and JavaScript Features I will start the explanation of the technical features to support the database project with a general introduction to databases, and then describe other programming techniques and HTML5, JavaScript, SQL, and PHP constructs. Keep in mind that you can see how read more..

  • Page - 390

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 378 Figure 10-24. Diagram for the database The so-called crow’s feet markings on the line connecting the two rectangles indicate the possible number of records involved. Each record of a site refers to exactly one record in the finders table. The two short vertical lines indicate at most one read more..

  • Page - 391

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 379 SQL SQL is a language just for database operations. Many online sources exist for SQL. Each statement, termed a query, invokes what would be considered a program. I introduce SQL by explaining the statements used in this project. The SQL queries will be constructed by PHP code and sent to the database as read more..

  • Page - 392

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 380 The statement for the finders table is similar: CREATE TABLE finders (finderid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, username char(50), epw char(64) I may have been able to make the username a primary key, but I decided to let MySQL do the work. Having created tables, now I’ll go read more..

  • Page - 393

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 381 The statement takes the two tables and joins them together when the WHERE condition is met. The s and the f are used to express the condition. The ORDER BY does what it sounds like with the DESC, indicating the most recent occurs first. The statement produces a table looking read more..

  • Page - 394

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 382 Hash Function A password that is stored as is in a database could be read by anyone with access to the database, and a password sent through the Internet could be read by anyone with the ability to spy on the packets being sent over the communication lines. An approach to avoid read more..

  • Page - 395

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 383 action does not proceed to addsite.php. If the encode function issues a return of true, then action does proceed. For the addsite task, the client operations include checking if the input has been submitted and is of the specified type. For the register.html script, a check is made read more..

  • Page - 396

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 384 an HTML document containing a form. The second member of the pair acts on the input to the form. Form action is discussed more in the next section. Since the tasks of PHP often involve creating character strings representing SQL queries or HTML markup, the language has special features for read more..

  • Page - 397

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 385 ends with standard HTML5. The code after the <?php and before the ?> will be explained following, in the “Results from SQL Queries” section. Briefly, the showsites.php script invokes an SQL query and uses the results to construct an HTML table to be displayed by the browser on read more..

  • Page - 398

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 386 You also can look ahead to Figure 10-26. Checking out the query string can be helpful during debugging. Information passed using the POST method is not visible, but is passed along as part of the HTTP protocol. The POST method presents a less cluttered appearance to the user, and this is read more..

  • Page - 399

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 387 practice, described as using self-referential scripts. The benefits are fewer files and, probably, an easier time making changes, because you do not have to refer to multiple files. However, the negative factors are that the scripts are more complex. Results from SQL Queries An SQL query produces two read more..

  • Page - 400

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 388 Figure 10-26. Showing the query string for the GET method The material that is dependent on the contents of the database consists of the value attributes of the option elements and the contents of the option elements. Here is the entire showsitesbycategory1.php script. Notice the <?php and read more..

  • Page - 401

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 389 extracts the value and assigns it to $cat. The next line prints a line of HTML. At this point, I need to remind you (because I often need to remind myself) that PHP extracts the value of variables when the variable names occur in strings. If the value of $cat is media, then the line print read more..

  • Page - 402

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 390 Building the Application and Making It Your Own You can make this application your own by using it as is and inserting the web sites that are of interest to you or a group for which you are building the project. You can also make it your own by building a totally different database. The read more..

  • Page - 403

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 391 Script(s) Task Uses Called or Used changepassword.html and completechangepassword.php Change the password changepassword.html uses sha256.js and drawroundarrowbox.js completechangepassword.php includes opendbo.php changepassword.html is called directly by the finders addsite.html and addsite.php Add a web site to the read more..

  • Page - 404

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 392 Table 10-2. Code for createresearchtables.php Code Line Description <?php Start PHP function createtable($tname,$fields) { Header for createtable; used for two tables global $DBname, $link; These two variables refer to the ones set in opendbo.php; the $DBname is not used $query = "DROP TABLE $tname"; read more..

  • Page - 405

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 393 Code Line Description <body> Body tag <?php Start PHP require("opendbo.php"); Bring in opendbo.php to make a connection to the database $tname = "sitesfinders"; Set the name for the sitesfinders table $fields="sid INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, stitle char(50), sdate read more..

  • Page - 406

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 394 Table 10-3. Scripts Concerning Finder Registration Code Line Description register.html <!DOCTYPE html> Not strictly necessary, but this is the standard header and may be required in the future; you can use HTML5 elements and features <html> html tag <head> Head tag <meta read more..

  • Page - 407

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 395 Code Line Description if (pw1 == document.f.cpw.value) { Check if the password and confirming password match document.f.pw.value = SHA256(pw1); If so, encode the password and replace it in the form document.f.cpw.value = document.f.pw.value; Use the same value for the confirming password read more..

  • Page - 408

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 396 Code Line Description <tr> Start row <td>User id (email address) </td><td><input type="email" name="un" required /></td></tr> Display the label (descriptor) for the un field and the input field; specify as type email and required <tr><td>Password read more..

  • Page - 409

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 397 Code Line Description <title>Complete registering finder</title> Complete title </head> Closing head tag <body> Body tag <?php Start PHP require("opendbo.php"); Bring in the opendbo.php script that connects to the database $tname = "finders"; Set the table name $finder = read more..

  • Page - 410

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 398 Code Line Description print ("The finder was NOT successfully added. <br>\n"); Print the not-success message } Close clause ?> End PHP </body> Closing body tag </html> Closing html tag changepassword.html <!DOCTYPE html> Doctype <html> html tag <head> Head tag read more..

  • Page - 411

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 399 Code Line Description var pw1 = document.f.oldpw.value; Set password value var npw = document.f.newpw.value; Set new password value if ((document.f.un.value.length<1) ||(pw1.length<1)) { Check if the password and username have each submitted alert("Need to enter User Name and Password. Please try again."); Display read more..

  • Page - 412

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 400 Code Line Description return false; Return false to prevent action going to PHP } Close clause } Close encode function </script> Closing script tag </head> Closing head tag <body> Body tag <form name="f" action="completechangepw.php" onSubmit="return encode();" read more..

  • Page - 413

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 401 Code Line Description </form> Closing form tag <canvas id="canvas" width="600" height="600"> Canvas element Your browser does not recognize canvas Message for old browsers </canvas> Closing canvas tag </body> Closing body tag </html> Closing html tag read more..

  • Page - 414

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 402 Code Line Description $query = "UPDATE $tname SET epw = '$epw2' WHERE username = '$finder' AND epw = '$epw1'"; Form the query to UPDATE (i.e., change) the epw field of any record with the indicated username equal to $finder and epw equal to $epw1; the query will make a change if the username and read more..

  • Page - 415

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 403 Code Line Description ctx.lineWidth = 4; Set the line width ctx.strokeStyle = colorstroke; Set the stroke color ctx.fillStyle = colorfill; Set the fill color ctx.font = "bold 16px sans-serif"; Set the font ctx.beginPath(); Start the path read more..

  • Page - 416

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 404 Code Line Description ctx.arc(x+rad,y+rad,rad,Math.PI,-.5*Math.PI,false); Draw an arc, a quarter of a circle ctx.closePath(); Close path ctx.fill(); Fill in ctx.stroke(); Draw outline ctx.fillStyle = colorstroke; Change the fill style to the outline (stroke) color ctx.fillText(text,x+rad,y+rad); Draw read more..

  • Page - 417

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 405 Code Line Description if (document.f.saveok.value!="No") { Check if the user changed the saveok field try { Try to do localStorage localStorage.setItem("researchun",document.f.un.value); Save the item under the name researchun with the value the un value read more..

  • Page - 418

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 406 Code Line Description if ((document.f.un.value.length<1) ||(pw1.length<1)) { Check if the user did not enter something for both un and pw1 alert("Need to enter User Name and Password. Please try again."); Display the message return false; Return false to prevent going to the PHP read more..

  • Page - 419

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 407 Code Line Description document.f.un.value = savedun; . . . then set it as the un value in the input field document.f.pw.value = savedpw; Also assume savedpw is good, and use it to set the pw value in the input field document.getElementById("greeting").innerHTML="Welcome read more..

  • Page - 420

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 408 Code Line Description Site: <input name="stitle" placeholder="Your name for site" required/><br/> Label and input field for site name Date: <input name="sdate" type="date" placeholder="YYYY-MM-DD" required/> <br/> Label and input field for date Site description: <br/> read more..

  • Page - 421

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 409 Code Line Description <head> Head tag <title>Complete adding site to research table</title> Complete title </head> Closing head tag <body> Body tag <?php Start PHP require("opendbo.php"); Bring in the file to connect to the database $tname = "sitesfinders"; Set the variable with the table read more..

  • Page - 422

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 410 Code Line Description if ($row=mysql_fetch_array($result)) { If there were any results, take the first one $fid = $row['finderid']; Extract the fid field $query = "INSERT INTO $tname values ('0','$stitle','$sdate','$surl','$sdesc','$scat','$fid')"; Form the query to insert a new record into the sitesfinders read more..

  • Page - 423

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 411 Code Line Description <?php Restart PHP section print ("Username: <input name='un' type='email' value='"); Using data sent print ($un."' />"); Display username print ("Password: <input name='pw' type='password' value='$epw' />"); Display dots for each character of encoded password (this read more..

  • Page - 424

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 412 Code Line Description </body> Closing body tag </html> Closing html tag removesites.php <!DOCTYPE html> Doctype <html> html tag <head> Head tag <title>Delele some sites</title> Complete title </head> Closing head tag <script type="text/javascript" read more..

  • Page - 425

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 413 Code Line Description document.f.pw.value = SHA256(pw1); Encode password return true; Return true to send control to the PHP script } Close clause } Close the encode function </script> Closing script tag <body> Body tag <?php Start PHP require("opendbo.php"); read more..

  • Page - 426

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 414 Code Line Description print("<tr>"); Print HTML markup to start row print ("<td><input type='checkbox' name='group[]' value='".$row['sid'] . "'/></td>"); Print HTML check box; the value is the ID for the site record print("<td> ".$row['stitle']."</td>"); read more..

  • Page - 427

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 415 Code Line Description </form> Closing form tag </body> Closing body tag </html> Closing html tag completeremovesites.php <!DOCTYPE html> Doctype <html> html tag <head> Head tag <title>Delele some sites</title> Complete title </head> Closing head tag <body> Body tag read more..

  • Page - 428

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 416 Code Line Description $ids = $_POST['group']; Extract the group input (this is an array) $deletelist = join (', ',$ids); Join the array elements together to form a string with commas in-between and assign to $deletelist $query = "DELETE FROM sitesfinders WHERE sid IN ($deletelist)"; Form a read more..

  • Page - 429

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 417 Code Line Description ?> End PHP </body> Closing body tag </html> Closing html tag The last group of scripts, shown in Table 10-5, includes the three for displaying the contents of the database. Now, I need to be clear as to what is meant by the term table. The PHP read more..

  • Page - 430

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 418 Code Line Description print("<table border='1'>"); Print the table tag to the HTML document print("<tr><th>Title</th><th>URL</th><th>Date </th><th>Description </th><th>Category </th><th>Finder </th></tr>"); Print the row with column headings to the read more..

  • Page - 431

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 419 Code Line Description showsitesbycategory1.php <!DOCTYPE html> Doctype <html> html tag <head> Head tag <title>List sites in a category</title> Complete title </head> Closing head tag <body> Body tag Pick the category you want: Text instructions <br/> Line break <form read more..

  • Page - 432

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 420 Code Line Description print ("<option value='$cat'>$cat</option><br>\n"); Print out to HTML an option element, with the $cat as the value and the visible contents } Close the while loop mysql_close($link); Close the connection to the database ?> End PHP </select> Closing read more..

  • Page - 433

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 421 Code Line Description print "Sites in $scat category <br/>"; Print out to HTML text for the display; line break require("opendbo.php"); Bring in the file to link to the database $query="SELECT * FROM sitesfinders as s JOIN finders as f WHERE s.finderid = f.finderid AND scategory read more..

  • Page - 434

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 422 Code Line Description print ("<td>".$row['sdate']."</td>"); . . . sdate print ("<td>".$row['sdescription']."</td>"); . . . sdescription print ("<td>".$row['username']."</td>"); . . . username print ("</tr>"); Print read more..

  • Page - 435

    CHAPTER 10 ■ WEB SITE DATABASE: USING PHP AND MYSQL 423 Summary In this chapter, you learned techniques in HTML5, JavaScript, MySQL, and PHP, including the following: • SQL commands for creating tables for a database • SQL commands for inserting, updating, selecting, and deleting records • PHP commands and techniques for composing SQL queries from read more..

  • Page - 436

    425 Index ■ A Accumulator, 303 addEventListener, 142 addListener function, 111 Adobe Flash, 332 ■ B Bouncing video, 53 animation automatic scrolling, 63 clearInterval(tid), 61 ctx.clearRect(0,0,cwidth,cheight), 61 displacement value, 62 init function, 61 moveandcheck function, 61, 62 setInterval(drawscene,50), 61 setInterval function, 61 tid = setInterval(drawscene,50), 61 videobounceC read more..

  • Page - 437

    ■ INDEX 426 adding and removing site records, 404 code for createresearchtables.php, 392 displaying information on sites, 417 end-users and database administrators, 390 finder registration scripts, 394 tasks by scripts, 390 client side vs. server side processing, 382, 383 critical requirements, 376 finders, 367 adding site, 371, 372 change password, 370, 371 read more..

  • Page - 438

    ■ INDEX 427 e-mail geolocation project function, 215 functions, 206 geocoder.geocode, 223 project code, 206 testing and uploading, 223 asynchronous request, 196 base location, 188, 189 checkit function, 202, 203 critical requirements base location, 195 client computer, 195 Google Maps Street View service, 194 GPS, 194 JavaScript processing, 195 latitude and longitude read more..

  • Page - 439

    ■ INDEX 428 TERRAIN map type, 138, 139 x1.png file, 141 mobile devices applications, 104 onLoad attribute, 104 portal construction, 105 pseudocode, 104 ROADMAP, 105 SATELLITE map, 105 TERRAIN map, 105 ■ H HTML5 logo, 1 body of document, 7, 8 Building section, 4 canvas element, 1 Chrome browser opening screen, 2 coordinate transformation, 8, 9 drawing paths read more..

  • Page - 440

    ■ INDEX 429 touchstart, 302 video preparation, positioning, and playing, 305 W3C, 302 firstpkel variable, 296 images and data acquisition, 294, 295 init function, 295 iPhone and iPad critical requirements, 293 game in progress, 291 jigsaw-puzzle-with-video-reward project, 293 opening screen, 289, 290 ready to play video, 291, 292 user interface construction, 289 video read more..

  • Page - 441

    ■ INDEX 430 HTML5 application, 103 location, 91, 95 meridians, 99 parallels, 99 teardrop marker, 103 values, 99, 100 Wolfram Alpha, 101 opening screen, 89, 90 satellite view, 96, 97 semitransparent shadow, 91 shadow/spotlight, 90, 91 slider, zoom, 91, 92 zoomed in to limit, 97, 98 zooming out and moving north, 92, 93 Map portal, Google Maps, 129 API (see Google Maps read more..

  • Page - 442

    ■ INDEX 431 fish throat photograph, 230 fish with throat fixed, 231 kami, 226 line drawings/images, 225 mountain/valley folds, 228 opening screen, 226 origami definition, 225 origamifish.html, 226 paused video, sink step, 229 photograph display, 247 sink fold, 228 skinny vertical line, 227 step after sink, 229, 230 step line drawing functions after making lips, 246 read more..

  • Page - 443

    ■ INDEX 432 ■ T TERRAIN map, 138, 139 THIS element, 10 toFixed method, 114 touchHandler function, 302 ■ U US states game, 321 application functions, 344 project code, 345 testing and uploading, 364 critical requirements, 329 doingjigsaw variable, 340 educational game, 321 elements creation, 335 Find the state, 322, 323 fullpage div, 342 image files Adobe Flash read more..

Write Your Review