Download presentation
Presentation is loading. Please wait.
1
Introduction to HTML
2
Contents Getting Started.. What is HTML? HTML web page Development How to create and View an HTML document? Basic HTML Document Format The HTML Basic tags HTML5
3
What the following term mean:
Web server: a system on the internet containg one or more web site Web site: a collection of one or more web pages Web pages: single disk file with a single file name Home pages: first page in website
4
Think about the followings before working your Web pages.
Think about the sort of information(content) you want to put on the Web. Set the goals for the Web site. Organize your content into main topics. Come up with a general structure for pages and topics.
5
What is HTML? Telling the browser what to do, and what props to use.
A serises of tags that are integrated into a text document. Tags are ; surrounded with angle brackets like this <B> or <I>. Most tags come in pairs exceptions: <P>, <br>, <li> tags … The first tag turns the action on, and the second turns it off.
6
The second tag(off switch) starts with a forward slash.
For example ,<B> text </B> can embedded, for instance, to do this: <HEAD><TITLE> Your text </HEAD></TITLE> it won't work. The correct order is <HEAD><TITLE> Your text </TITLE></HEAD> not case sensitivity. Many tags have attributes. For example, <P ALIGN=CENTER> centers the paragraph following it. Some browsers don't support the some tags and some attributes.
7
Basic HTML Document Format
<HEAD> <TITLE>WENT'99</TITLE> </HEAD> <BODY> Went'99 </BODY> </HTML> See what it looks like:
8
How to Create and View an HTML document?
1.Use an text editor such as Editpad to write the document. 2.Save the file as filename.html on a PC. This is called the Document Source. 3.Open IE (or any browser) Off-Line 4.Switch to Netscape 5.Click on File, Open File and select the filename.html document that you just created. 6.Your HTML page should now appear just like any other Web page in Netscape.
9
7.You may now switch back and forth between the Source and the HTML Document
switch to Notepad with the Document Source make changes save the document again switch back to Netscape click on RELOAD and view the new HTML Document switch to Notepad with the Document Source......
10
Tags in head <HEAD>...</HEAD>-- contains information about the document <TITLE>...</TITLE>-- puts text on the browser's title bar.
11
Tags in Body Let's talk Text Heading: <H1> </H1> Center:<Center> </Center> Line Break <P> ,<Br> Phrase Markups: <I></I> ,<B></B> Create a List Unordered list : <UL><li> Ordered list: <OL><li> Nested
12
Use <IMG SRC=imagefilename> tags
Add Images Use <IMG SRC=imagefilename> tags How to specify Relative pathnames Attributes of IMG tag -width,height -Alt -Align -<Img src=my.gif width=50 height=50 align=right alt=“My image”>
13
Use <A href=filename|URL></a>tags
Add some Link Use <A href=filename|URL></a>tags How to specify Relative pathnames Kinds of URLs - - ftp://ftp.foo.com/home/foo - gopher://gopher.myhost.com/ - news://news.nuri.net -
14
<BODY BACKGROUND=bgimg.gif >
How to make colors changes? Hexadecimal number : Color names : <Font color=white> Changing the Background color <BODY BGCOLOR=#19378a> Changing Text color <BODY BGCOLOR=#19378a TEXT=#ffffff LINK=#ffff VLINK=#66ffff> Spot color <FONT COLOR=#66ffcc>WENT'99</FONT> Image Background <BODY BACKGROUND=bgimg.gif >
15
How to specify Relative pathnames
The current HTML document is my.html and the current directory is Iam C:\- Iam -my.html -your.html Type this ; <A href=your.html>Your link </A> Child -your.html Type this ; <A href=Child/your.html>Your link </A> C:\- Iam -my.html Sister -your.html Type this ; <A href=../Sister/your.html>Your link </A> C:\- Mother -your.html Iam -my.html Type this ; <A href=../your.html>Your link </A> Go to Back
16
How to specify Relative pathnames
The HTML document is my.html and the image file is dragonfly.gif C:\- Iam -my.html ☞ Type this ; <IMG SRC=dragonfly.gif> -dragonfly.gif C:\- Iam -my.html ☞ Type this ; <IMG SRC=Image/dragonfly.gif> Image C:\- Iam -my.html ☞ Type this ; <IMG SRC=../Image/dragonfly.gif> C:\- Image -dragonfly.gif ☞ Type this ; <IMG SRC=../dragonfly.gif> Iam -my.html Go to Back
17
Dedicated HTML editor software
Microsoft FrontPage Dreamweaver
18
Introduction to HTML5
19
Software Requirements
To write HTML5 and JavaScript code, you need a text editor, a browser, and, sometimes, a web server (it can be locally hosted on your personal desktop). The text editors we recommend for Windows are PSPad, TextPad or EditPlus (but you can use Notepad if you have to). The text editors we recommend for Mac are TextWrangler, TextMate or TextEdit. If you're on a Linux system, you've got plenty of text editors built-in, and we trust you don't need us to tell you about them. We hope you've got the browser bit covered and have installed at least two browsers (see the previous page). If not, do it now. It's also worth your time to learn how to use the browser developer tools; each of the major browsers has built-in tools you can use to inspect the JavaScript console (you can see errors as well as output you display using console.log, a handy alternative to alert), web storage usage, the DOM, CSS style that's been applied to elements, and much much more. Some browsers even have plug-ins for additional developer tools. You don't need the developer tools to get through the book, but if you're willing to spend the time to investigate how to use these, it will make development easier. Some HTML5 features and JavaScript APIs require that you serve files from a real web server rather than by loading a file (i.e., your URL will start with rather than file:// ). We've identified which examples you'll need a server for in the appropriate places in the book, but if you're motivated, we recommend you go ahead and install a server on your computer now. For Mac and Linux, Apache comes built-in, so you'll just need to make sure you know how to access it and where to put your files so you can serve them using your local server. For Windows, you'll need to install Apache or IIS; if you go the Apache route, there are plenty of open source tools like WAMP and XAMPP that are fairly easy to install.
20
HTML has been on a wild ride
HTML has been on a wild ride. Sure, HTML started as a mere markup language, but more recently HTML's put on some major muscle.
21
HTML 5 Is still a markup language!
22
Now you probably already know all about HTML markup (otherwise known as structure) and you know all about CSS style (presentation), but what you've been missing is JavaScript (behavior).
23
Javascript Now we've got a language tuned for building web applications with Web storage, 2D drawing, offline support, sockets and threads, and more. And to speak this language you've got to go beyond HTML5 markup and into the world of the DOM, events, and JavaScript APIs. If all you know about are structure and presentation, you can create some great looking pages, but they're still just pages. When you add behavior with JavaScript, you can create an interactive experience; even better, you can create full blown web applications.
24
creating web applications with HTML5 and JavaScript, and we give you everything you need to know to build them, including: how to add interactivity to your pages, how to communicate with the world of Web services, and how to use the great new APIs being developed for HTML5. Here are just some of the things you'll learn in Head First HTML5 Programming: Learn how to make your pages truly interactive by using the power of the DOM. Finally understand how JavaScript works and take yourself from novice to well-informed in just a few chapters. Learn how JavaScript APIs fit into the HTML5 ecosystem, and how to use any API in your web pages. Use the Geolocation API to know where your users are. Bring out your inner artist with Canvas, HTML5's new 2D drawing surface. Go beyond just plugging a video into your pages, and create custom video experiences. Learn the secret to grabbing five megabytes of storage in every user's browser. Improve your page's responsiveness and performance with Web workers. And much more.
25
Canvas Rendering Contexts
Every HTML5 canvas element must have a context. The context defines what HTML5 Canvas API you’ll be using. The 2d context is used for drawing 2D graphics and manipulating bitmap images. The 3d context is used for 3D graphics creation and manipulation. The latter is actually called WebGL and it’s based on OpenGL ES.
26
What is HTML5 Canvas? The canvas element is an element defined in HTML code using width and height attributes. The real power of the canvas element, however, is accomplished by taking advantage of the HTML5 Canvas API. This API is used by writing JavaScript that can access the canvas area through a full set of drawing functions, thus allowing for dynamically generated graphics.
27
What’s so Great About HTML5 Canvas?
Here are some reasons you might want to consider learning to use HTML5’s canvas feature: Interactivity. Canvas is fully interactive. It can respond to a user’s actions by listening for keyboard, mouse, or touch events. So a developer is not restricted to only static graphics and images. Animation. Every object drawn on the canvas can be animated. This allows for all levels of animations to be created, from simple bouncing balls to complex forward and inverse kinematics. Flexibility. Developers can create just about anything using canvas. It can display lines, shapes, text, images, etc. — with or without animation. Plus, adding video and/or audio to a canvas application is also possible. Browser/Platform Support. HTML5 Canvas is supported by all major browsers and can be accessed on a wide range of devices including desktops, tablets, and smart phones. Popularity. Canvas popularity is rapidly and steadily growing so there is no shortage of resources available. It’s a web standard. Unlike Flash and Silverlight, Canvas is open technology that’s part of HTML5. And although not all of its features are implemented in all browsers, developers can be certain canvas will be around indefinitely. Develop once, run everywhere. HTML5 Canvas offers great portability. Once created, Unlike Flash and Silverlight, a canvas application can run almost anywhere — from the largest computers to the smallest mobile devices. Free and accessible development tools. The basic tools for creating HTML5 canvas applications are just a browser and a good code editor. Plus, there are many great and free libraries and tools to help developers with advanced canvas development.
28
What Applications Can You Create with HTML5 Canvas?
OK, canvas is great. But what exactly can use it for? Let’s see. Gaming. The HTML5 Canvas’ feature set is an ideal candidate for producing all sorts of 2D and 3D games. Advertising. HTML5 Canvas is a great replacement for Flash-based banners and ads. It has all the needed features for attracting buyers’ attention. Data Representation. HTML5 can collect data from global data sources and use it to generate visually appealing and interactive graphs and charts with the canvas element. Education and Training. HTML5 canvas can be used to produce effective and attractive learning experiences, combining text, images, videos, and audio. Art and Decoration. With a little bit of imagination and canvas’s wide variety of colors, gradients, patterns, transparency, shadows, and clipping features, all kinds of artistic and decorative graphics can be drawn. Now that we know why we should learn canvas, let’s look at the basics of HTML5 Canvas and how to start using it.
29
Background HTML5 is the latest/soon to be version of
HyperText Markup Language (HTML): text with tags for content JavaScript: scripting/programming language for interactivity, dynamic presentation Cascading Style Sheets: formatting
30
Many new features, for support of semantic web, dynamic/interactive websites
CAUTION: definition not official. Browser support evolving.
31
New features include: Semantic elements: header, footer, section, article, others. canvas for drawing paths of rectangles, arcs, lines, images mouse events localStorage (variation of cookies) audio & video elements including drawing video on canvas
32
This Tutorial Build Favorite sites Build Drawings Build Coin toss
review HTML structure, new elements) Build Drawings draw rectangles, arcs, lines on canvas Build Coin toss event handling, draw text and images on canvas Find video clips & convert. Add video to favorite sites or make it stand-alone. Build Bouncing Video draw video, create mask, timed event Build geolocation application, including Google Maps API app and localStorage Preview Essential Guide to HTML5
33
Tools TextPad or NotePad Compatible browser
Dreamweaver okay but it does cost. Compatible browser Firefox: works for all examples, including masked video and geolocation Chrome and Safari work for most examples IE9 being tested now
34
HTML review Elements consist of opening tag, contents of the element and closing tag. Tags have attributes. <a href="nextpage.html">NEXT </a> Some elements/tags are singletons <img src="logo.gif" width="100"/>
35
Document Object Model (DOM) defines relationships, attributes & methods of objects.
36
Advice HTML does not recognize white space.
You need to make spacing and line breaks explicit. For your readability, put line breaks and spaces. My objective often is to squeeze things in one slide. This isn't your objective!
37
HTML template <!DOCTYPE html> <html lang="en">
<head> <title></title> <meta charset="utf-8"> </head> <body> </body> </html>
38
Favorite Sites overview for this example: <!DOCTYPE html>
<html lang="en"> <head> <title> </title> <meta charset="UTF-8"> <style> </style> // for header and article and img <script> </script> </head> <body> content: header, article for each site </body> </html>
39
<style> header {font-family:Georgia,"Times New Roman",serif; text-align:center; font-size:30px; display:block; } article { text-align:left; font-size:20px; margin:20px; display:block; font-family:"Century","Tahoma", sans-serif; } img {display:block;} </style> <script> document.write(Date()); </script> </head>
40
<body> <header>Favorite Sites </header> <article> Google <a href=" <img src=“kkkkk.jpg" width="100"/> </article> </html>
41
Comments Remember: spaces, line breaks need to be inserted explicitly
My first attempt was to use <br/> to force images to their own line. I changed to using a style to keep formatting in the <style> section. need not be so pure! GO! - get information, look up other CSS, ask!
42
2nd set of projects: Drawing
canvas element Use code to define a so-called context. Methods of this object do the work! Screen geometry: upper left corner is origin. Colors defined by red-green-blue values or a small set of named colors, will show hexadecimal example later. stroke versus fill draw Rectangles
43
500,0,default color,20 by 20, fill 0,0, default color, 10 by 10, stroke rgb(200,0,100) 0,300,green,30 by 30, stroke 500,300, 50 by 50, fill
44
var ctx; function init() {
<!DOCTYPE html> <html lang="en"><head><title>Four rectangles</title> <meta charset="UTF-8"><script> var ctx; function init() { ctx = document.getElementById('canvas').getContext('2d'); ctx.lineWidth = 2; ctx.strokeRect(0,0,10,10); ctx.fillRect(500,0,20,20); ctx.strokeStyle = "green"; ctx.fillStyle = "rgb(200,0,100)"; ctx.strokeRect(0,300,30,30); ctx.fillRect(500,300,50,50); } </script> </head> <body onLoad="init();"> <canvas id="canvas" width="600" height="400"> Your browser doesn't support the HTML5 element canvas.</canvas> </body> </html>
45
Errors JavaScript is scripting language: interpret statements at execution time. NOT compiled, with error messages Semantic errors (errors of meaning) are more difficult to detect and fix! Syntactic errors are errors of form, analogous to grammatical errors FireFox Tools/Error Console can help Most common: bad bracketing ctx.fillStyle("rgb(200,0,100)"); fillStyle is attribute,not method
46
Comments The drawing is done in the init function which is called when the body element is loaded. The canvas element with id="canvas" does not exist until the body is loaded. Default color is black. Red green blue values each are 0 to 255 (8 bits of intensity). The strokeStyle and the fillStyle are attributes, not methods. GO: experiment with colors (by name) and rgb (note the quotation marks) and location and width and height.
47
More comments Drawings are …paint on the canvas.
These rectangles are not objects to be moved or referenced later. Use ctx.clearRect method to erase. Need to do calculations to detect hits. See memory game in book. Alternative is dynamic placement of html markup See quiz, hangman.
48
Next drawing Paths created with arcs and line segments
Arcs are portions of circles, created using radians in place of degrees. Math.PI is available for use. A complete circle can be drawn from 0 to 2*Math.PI or –Math.PI to Math.PI, etc. Arcs can be stroke or fill.
49
Angles PI*3/2 PI 0 (=2*PI) .20 * PI PI/4 .80*PI
true means counter-clockwise! PI/2
50
arcs ctx.arc (x of center, y of center, radius, starting angle, finishing angle, true for counter-clockwise) No drawing (ink) at the center! This is important when connecting arcs and lines. EXPERIMENT
51
4 distinct paths, each made up of 1 arc.
Default, "red" and "brown"
52
Strategy Use variables with some variable values defined in terms of others. Circle face and two eyes. Smile is (partial) arc. Brown eyes and red smile. body element same as before. You can add the code for this to your rectangles drawing.
53
var ctx; var headx = 100; //center of face x coord. var heady = 200; // center of face y coord. var headrad = 50; //radius of face var smileoffsetx=0; //smile center x is same as face var smileoffsety = 15; //smile center y further down var smilerad=20; // smile radius var eyeoffsety = -10; //eyes up from center var lefteyeoffsetx = -15; //left eye var righteyeoffsetx = -lefteyeoffsetx; //right var eyerad = 8; // eye radius
54
function init() { ctx = document.getElementById('canvas').getContext('2d'); ctx.lineWidth = 5; ctx.beginPath(); ctx.arc(headx,heady,headrad,0,2*Math.PI,true); ctx.closePath(); ctx.stroke(); …
55
ctx.strokeStyle = "red"; ctx.beginPath(); ctx.arc(headx+smileoffsetx,heady+smileoffsety, smilerad,.80*Math.PI,.20*Math.PI,true); ctx.stroke(); ctx.fillStyle = "brown"; ctx.arc(headx+lefteyeoffsetx,heady+eyeoffsety,eyerad, 0,2*Math.PI,true); ctx.fill(); ctx.beginPath(); ctx.arc(headx+righteyeoffsetx,heady+eyeoffsety,eyerad,0,2*Math.PI,true); ctx.fill(); }
56
Comments The fill and stroke calls close the path.
Also, can close a path with closePath() Using variables makes code more flexible and easier to see relationships. GO: draw arcs, changing colors, sizes, etc. NOTE: can draw non-circular ovals using transformations: scale. Check out the hangman game in book!
57
Next drawing: star For drawing lines (and arcs), think of moving a pencil versus drawing (preparing to draw) a line segment nothing is drawn until the stroke or fill Use an array with coordinates for 5 points Use an array to hold names of 3 colors button element
58
opening screen
59
after 1st press of button
60
after next press
61
after next press
62
show body first <body onLoad="init();">
<canvas id="canvas" width="600" height="400"> Your browser doesn't support the HTML5 element canvas. </canvas> <button onClick="makestar();">Make Star </button> </body> </html>
63
variables (in script element)
var ctx; var pts=[ //5 points for star: rough drawing [100,35], [60,10], [20,35], [35,100], [85,100] ]; var colors=["red","white","blue"]; //used in succession var c=0; // points to next color
64
variables (in script element)
var ctx; var pts=[ //5 points for star: rough drawing [100,35], [60,10], [20,35], [35,100], [85,100] ]; var colors=["red","white","blue"]; //used in succession var c=0; // points to next color
65
variables (in script element)
var ctx; var pts=[ //5 points for star: rough drawing [100,35], [60,10], [20,35], [35,100], [85,100] ]; var colors=["red","white","blue"]; //used in succession var c=0; // points to next color
66
variables (in script element)
var ctx; var pts=[ //5 points for star: rough drawing [100,35], [60,10], [20,35], [35,100], [85,100] ]; var colors=["red","white","blue"]; //used in succession var c=0; // points to next color
67
variables (in script element)
var ctx; var pts=[ //5 points for star: rough drawing [100,35], [60,10], [20,35], [35,100], [85,100] ]; var colors=["red","white","blue"]; //used in succession var c=0; // points to next color
68
function init() { ctx = document.getElementById('canvas').getContext('2d'); } function makestar() { ctx.clearRect(0,0,600,400); ctx.fillStyle=colors[c]; c = c +1; // can reduce to one line using colors[c++] c = (c<3)?c:0; ctx.beginPath(); ctx.moveTo(pts[0][0],pts[0][1]); ctx.lineTo(pts[3][0],pts[3][1]); ctx.lineTo(pts[1][0],pts[1][1]); ctx.lineTo(pts[4][0],pts[4][1]); ctx.lineTo(pts[2][0],pts[2][1]); ctx.lineTo(pts[0][0],pts[0][1]); ctx.stroke(); //outline (necessary for white star! ctx.fill(); }
69
Comments Your assignment: do something with a button. It does not have to be a star. But do use moveTo and lineTo. You can combine with rectangles (separate from paths) and arcs (can combine with lines). Try stroke and fill Can include multiple moveTo think of picking up your pen and moving to a new spot on the paper/canvas.
70
Fancier stars Code to draw star more precisely
Position each star randomly on canvas. Add star with each button press Increase number of colors. improve coding for robustness
71
after many presses
72
Strategy reuse code for makestar, with modification
remove clearRect method add a call to buildstar that re-creates the pts array add items to colors array remove 3 from the code! position, size, and rotation of star created using calls to Math.random.
73
variables var ctx; var angle = 2*Math.PI/5; var pts=[ ];
var colors=["red","white","blue","purple","yellow","teal"]; var c=0;
74
function makestar() { buildstar(); ctx.fillStyle=colors[c++]; c = (c<colors.length)?c:0; ctx.beginPath(); ctx.moveTo(pts[0][0],pts[0][1]); ctx.lineTo(pts[3][0],pts[3][1]); ctx.lineTo(pts[1][0],pts[1][1]); ctx.lineTo(pts[4][0],pts[4][1]); ctx.lineTo(pts[2][0],pts[2][1]); ctx.lineTo(pts[0][0],pts[0][1]); ctx.stroke(); ctx.fill(); }
75
function buildstar() {
pts = []; var x=500*Math.random(); //all these arbitrary var y = 300*Math.random(); var r=50*Math.random(); var sangle = Math.random()*angle; for(var i=0;i<5;i++) { var a = i*angle + sangle; var px = x+r*Math.cos(a); var py = y-r*Math.sin(a); pts.push([px,py]); }
76
Comments Lesson of these examples is that drawings are dynamic!
can be done under specific circumstances in a program using different values Do this if there is time. Consider changing names of colors constants draw something instead of or in addition to the star ?
77
Next: coin flip Draw image from image file of head or tail on canvas where player clicks mouse event handling: listen for mouse click draw image made from external file Draw text (with directions) on canvas
78
opening screen
79
after mouse click
80
Strategy Need to locate/identify file address for images
can be in same folder (use relative address) or use full URL Image objects with src attribute font set for context (ctx) event handling done for canvas element NOT context. Sets up call to function that has 1 parameter Does require browser specific code to get mouse coordinates. (Sigh….) use technique of checking for presence of attribute
81
Strategy, cont. Fonts are from what is available on the client computer. draw outline (strokeRect) to show player where canvas is. Alternative to color names or rgb is hexadecimal. use PhotoShop or Paint Shop Pro Note that my code makes adjustment to put middle of image where mouse was clicked.
82
variables var ctx; var canvas1; var head = new Image();
var tail = new Image(); head.src = "head.gif"; tail.src = "tail.gif"; var coinwidth = 100; var coinheight = 100;
83
functions function init() {
ctx = document.getElementById('canvas').getContext('2d'); canvas1 = document.getElementById('canvas'); canvas1.addEventListener('click',flip,false); ctx.font = "italic 20px Accent"; ctx.fillStyle = "#dd00ff"; ctx.strokeRect(0,0,600,400); ctx.fillText("Click on canvas to flip a coin.",10,20); }
84
function flip(ev) { var mx; var my; ctx.clearRect(0,0,600,400); if ( ev.layerX || ev.layerX == 0) { // Firefox mx= ev.layerX; my = ev.layerY; } else if (ev.offsetX || ev.offsetX == 0) { // Opera mx = ev.offsetX; my = ev.offsetY; } if (Math.random()>.5) { ctx.drawImage(head,mx-50,my-50,coinwidth,coinheight); } else { ctx.drawImage(tail,mx-50,my-50,coinwidth,coinheight);} ctx.strokeRect(0,0,600,400); ctx.fillText("Click on canvas to flip a coin.",10,20); }
85
Comments You need to acquire two images to represent the coin faces.
download to same folder or use exact, complete address You can go into Word, or equivalent, to see available fonts. more in book AND online. Go!
86
Background on audio & video
This is native support (no need for plugins), no dependence on YouTube. Issue: Multiple formats (aka codecs) for each. Different browsers recognize different formats. Situation MAY improve: may be standardization. Good news: the <audio> and <video> elements provide way to reference multiple files and let browser choose (though order does seem to be important).
87
Audio & video elements <audio autobuffer>
<source src="crowdohh.ogg" /> <source src="crowdohh.mp3" /> </audio> <video controls="controls"> <source src="sfire3.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> <source src="sfire3.theora.ogv" type='video/ogg; codecs="theora, vorbis"'> <source src="sfire3.webmvp8.webm" type="video/webm; codec="vp8, vorbis"'"> </video>
88
Our goal now Find and download video files.
Use Miro Converter to produce other formats. Put audio into one of existing projects. Put video into one of existing projects. Build video bouncing ball. Look at book's rock-paper-scissors for playing specific sounds at specific times. Look at book's quiz for keeping video invisible and playing it only when quiz round complete.
89
Acquire video Make your own.
Find on-line. Site lets you specify a URL and choose from the videos to download. Respect intellectual property!!! Respect personal privacy (of friends & family, etc.)!!!
90
Produce all formats Produce formats for all browsers:
Download the program. The original file can be in several different formats, including flv (Flash format, used by YouTube). Follow directions: should produce the 3 formats: mp4, theora.ogv, webmvp8.webm
91
Next: Video Put video element in your favorite sites or something else or ??? Test using Firefox, Chrome and Safari. PATIENCE!!
92
Next: Bouncing video Two versions
move around video element use drawImage to place video on canvas (works in FireFox) Doing this makes it easier to draw mask. Otherwise, difficult to position. "Not quite ready for prime time". Need to put in code to wait until video all downloaded.
93
Strategy Use setInterval to invoke [my] drawscene function
re-position video. Check against [virtual] walls. Apply angle of incidence equal angle of reflection (easy to do) use strokeRect to draw box NOTE: the loop attribute did not work, so I set up event handling for video ended event.
94
Function table init Called by action of onLoad in <body> restart
… addEventListener in init drawscene … setInterval in init. This is different in two versions moveandcheck Called in drawscene
95
Bouncing video rectangle
canvas and video distinct elements
96
Video is in motion
97
Style section Positioning and layering (my term).
Note: to change z-index by JavaScript, use zIndex. <style> #vid {position:absolute; visibility:hidden; z-index: 0; } #canvas {position:absolute; z-index:10;} </style>
98
<script type="text/javascript">
var ctx; var cwidth = 900; var cheight = 600; var ballrad = 50; var boxx = 20; var boxy = 30; var boxwidth = 850; var boxheight = 550; var boxboundx = boxwidth+boxx-2*ballrad; var boxboundy = boxheight+boxy-2*ballrad; var inboxboundx = 0; var inboxboundy = 0; var ballx = 50; var bally = 60; var ballvx = 2; var ballvy = 4; var v;
99
function init(){ ctx = document.getElementById('canvas').getContext('2d'); v = document.getElementById("vid"); v.addEventListener("ended",restart,false); v.style.left = ballx; v.style.top = bally; v.width = 2*ballrad; v.height = 2*ballrad; v.play(); v.style.visibility = "visible"; setInterval(drawscene,50); }
100
function restart() { v.currentTime=0; v.play(); }
101
function drawscene(){
ctx.lineWidth = ballrad; ctx.clearRect(boxx,boxy,boxwidth,boxheight); moveandcheck(); v.style.left = ballx; v.style.top = bally; ctx.strokeStyle ="rgb(200,0,50)"; ctx.strokeRect(boxx,boxy,boxwidth,boxheight); //box }
102
function moveandcheck() {
var nballx = ballx + ballvx; var nbally = bally +ballvy; if (nballx > boxboundx) { ballvx =-ballvx; nballx = boxboundx; } if (nballx < inboxboundx) { nballx = inboxboundx ballvx = -ballvx; } if (nbally > boxboundy) { nbally = boxboundy; ballvy =-ballvy; } if (nbally < inboxboundy) { nbally = inboxboundy; ballvy = -ballvy; } ballx = nballx; bally = nbally; }
103
<body onLoad="init();">
<video id="vid" loop="loop" preload="auto"> <source src="joshuahomerun.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> <source src="joshuahomerun.theora.ogv" type='video/ogg; codecs="theora, vorbis"'> <source src="joshuahomerun.webmvp8.webm" type='video/webm; codec="vp8, vorbis"'> Your browser does not accept the video tag. </video> <canvas id="canvas" width="900" height="600"> This browser doesn't support the HTML5 canvas element. </canvas> </body>
104
Bouncing video circle Works in Firefox. video used in drawImage.
A mask is created: a box with a hole positioned over the video to produce a circular
105
Video is in motion
106
<script> var ctx; var cwidth = 900; var cheight = 600; var ballrad = 50; var boxx = 20; var boxy = 30; var boxwidth = 850; var boxheight = 550; var boxboundx = boxwidth+boxx-2*ballrad; var boxboundy = boxheight+boxy-2*ballrad; var inboxboundx = 0; var inboxboundy = 0; var ballx = 50; var bally = 60; var ballvx = 2; var ballvy = 4; var maskrad; var v;
107
v = document.getElementById("vid");
function init(){ ctx = document.getElementById('canvas').getContext('2d'); v = document.getElementById("vid"); v.addEventListener("ended",restart,false); // because loop doesn't work on FF v.width = v.videoWidth/3; v.height = v.videoHeight/3; videow = v.width; videoh = v.height; maskrad = .4*Math.min(videow,videoh); v.play(); setInterval(drawscene,50); }
108
function restart() { v.currentTime=0; v.play(); }
109
function drawscene(){
ctx.lineWidth = ballrad; ctx.clearRect(0,0,boxwidth+boxx,boxheight+boxy); ctx.fillStyle="rgb(255,255,255)"; //white moveandcheck(); ctx.drawImage(v,ballx+boxx, bally+boxy, v.width,v.height); ctx.beginPath(); ctx.moveTo(ballx+boxx,bally+boxy); ctx.lineTo(ballx+boxx+v.width,bally+boxy); ctx.lineTo(ballx+boxx+v.width,bally+boxy+v.height); ctx.lineTo(ballx+boxx,bally+boxy+v.height); ctx.lineTo(ballx+boxx,bally+boxy); ctx.arc(ballx+boxx+.5*v.width,bally+boxy+.5*v.height,maskrad,0, Math.PI*2,true); ctx.fill(); //draw white mask on top of video, letting just circle show ctx.strokeStyle ="rgb(200,0,50)"; ctx.strokeRect(boxx,boxy,boxwidth,boxheight); //box }
110
function moveandcheck() {
var nballx = ballx + ballvx; var nbally = bally +ballvy; if (nballx > boxboundx) { ballvx =-ballvx; nballx = boxboundx; } if (nballx < inboxboundx) { nballx = inboxboundx ballvx = -ballvx; } if (nbally > boxboundy) { nbally = boxboundy; ballvy =-ballvy; } if (nbally < inboxboundy) { nbally = inboxboundy; ballvy = -ballvy; } ballx = nballx; bally = nbally; }
111
<body onLoad="init();">
<video id="vid" loop="loop" preload="auto"> <source src="joshuahomerun.mp4" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'> <source src="joshuahomerun.theora.ogv" type='video/ogg; codecs="theora, vorbis"'> <source src="joshuahomerun.webmvp8.webm" type='video/webm; codec="vp8, vorbis"'> Your browser does not accept the video tag. </video> <canvas id="canvas" width="900" height="600"> This browser doesn't support the HTML5 canvas element. </canvas> </body>
112
Next: Maps app Use Google Maps API to bring up map at current location. Respond to clicking by placing a marker and calculating distance. Provide way to change to fixed set of locations or the last marker. need to give permission to Share Location Works in Chrome and Firefox. Does not work in Safari for Windows.
113
Opening screen
114
Brings up ….
115
After click on map
116
After choose CUNY
117
Mapping Google Maps API (and other applications) defines positions using special latitude/longitude data object Access to Google Map is created for a place in the HTML document, using specified map options HTML has a specification for doing geolocation. navigator.geolocation produces latitude and longitude values
118
How to get positions? Google Maps get to a map
Browser location javascript:void(prompt('',gApplication.getMap().getCenter())); OR Click on green beaker and enable the drop latlng marker right click then normal click
119
My program Tries to use the geolocation
Gives user option to pick base location User can click on map and find distance from base center. Can change base to last clicked on position. General access to Google Maps features.
120
Basics if (navigator.geolocation) checks if this object exists. Does NOT cause any errors. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition (handler,problemhandler); } handler when things go okay. problemhandler when there are errors, including user deciding not to share location.
121
Create/Access Google Maps
map = new google.maps.Map(document.getElementById("place"), myOptions); brings up Google Maps in the div with id "place" using the parameters in myOptions. <div id="place" style="width:600px; height:400px"></div> NOTE: use of % for width and height did not work when <!DOCTYPE html> used.
122
style, external script <style>
header {font-family:Georgia,"Times New Roman",serif; font-size:20px; display:block; } </style> <script type="text/javascript" src=" <script language="Javascript">
123
init() code function init() { if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition (handler,problemhandler); } else { if (document.getElementById("place")) { document.getElementById("place").innerHTML = "I'm sorry but geolocation services are not supported by your browser"; document.getElementById("place").style.color = "#FF0000"; } } }
124
function handler(position) {
var mylat = position.coords.latitude; var mylong = position.coords.longitude; makemap(mylat,mylong); }
125
error handling function problemhandler(prob) { switch(prob.code) {
case 1: document.getElementById("place").innerHTML = "User declined to share the location information."; break; case 2: document.getElementById("place").innerHTML = "Errors in getting base location."; case 3: document.getElementById("place").innerHTML = "Timeout in getting base location."; } document.getElementById("header").innerHTML = "Base location needs to be set!"; }
126
variables var listener; var map; var markersArray =[]; var blatlng;
var myOptions; var locations = [ [ , , "Memphis, TN"], [ , ,"Purchase College/SUNY"], [ , ,"IIT"] ];
127
create/access map function makemap(mylat, mylong) {
blatlng = new google.maps.LatLng(mylat,mylong); myOptions = { zoom: 14, center: blatlng, mapTypeId: google.maps.MapTypeId.ROADMAP}; map = new google.maps.Map(document.getElementById("place"), myOptions); listener = google.maps.event.addListener(map, 'click', function(event) { checkit(event.latLng);}); }
128
response to click on map
function checkit(clatlng) { var distance = dist(clatlng,blatlng); distance = Math.floor((distance+.005)*100)/100; var distanceString = String(distance)+" miles"; marker = new google.maps.Marker({ position: clatlng, title: distanceString, map: map }); markersArray.push(marker); document.getElementById("answer").innerHTML = "The distance from base to most recent marker is "+String(distance) +" miles."; }
129
distance function function dist(point1, point2) {
//spherical law of cosines //var R = 6371; // km var R = 3959; // miles var lat1 = point1.lat()*Math.PI/180; 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; return d; }
130
change base using radio buttons
function changebase() { for(var i=0;i<locations.length;i++) { if (document.f.loc[i].checked) { makemap(locations[i][0],locations[i][1]); document.getElementById("header").innerHTML = "Base location is "+locations[i][2]; } return false;
131
</script> </head> <body onload="init();">
<header id="header">Base location is your current geolocation</header> <div id="place" style="width:600px; height:400px"></div> <div id="answer"></div> Change base location: <br/> <form name="f" onSubmit=" return changebase();"> <input type="radio" name="loc" /> Memphis<br/> <input type="radio" name="loc" /> Purchase College<br/> <input type="radio" name="loc" /> Illinois Institute of Technology<br/> <input type="submit" value="CHANGE"> </form> </body> </html>
132
Variation Geolocation returns accuracy and, maybe, other information, including altitude. These applications mark the center with a red x and display other information Note: accuracy is given in meters in both cases
133
Critical code Uses custom image for marker var xmarker = "x1.png"; …
marker = new google.maps.Marker({ position: blatlng, title: "center", icon: xmarker, map: map });
134
getCurrentPosition 3rd parameter to getCurrentPosition call
positionopts = {enableHighAccuracy: true} ; … navigator.geolocation.getCurrentPosition(handler, problemhandler, positionopts); Add form coutput for output document.coutput.lat.value = mylat; document.coutput.lon.value = mylong; document.coutput.acc.value = position.coords.accuracy; document.coutput.alt.value = position.coords.altitude; document.coutput.altacc.value = position.coords.altitudeAccuracy; document.coutput.heading.value = position.coords.heading; document.coutput.speed.value = position.coords.speed;
135
Next application: persistent storage
Normal situation: no changes to client computer beyond downloaded files. cookies invented (with a pleasing name) to be files associated with each browser to be used only by same server site. convenience: IDs and passwords, preferences, etc. behavioral marketing! Early HTML supported cookies. localStorage is a new variation. CAUTION: Firefox requires the program to run on a server! Chrome allows running locally.
136
Opening (after permission)
137
New base
138
Objective: add to maps app
3 buttons: store base, retrieve base stored, change base to last marker localStorage used name-value pairs. Do error checking! check for ability to do localStorage check if there is a stored time.
139
Strategy Three buttons, invoking store(), retrieve(), and changebasetomarker() Use try { } catch(e) { } . The code in try will NOT trigger an error, but if there is one, will go to catch. Also use typeof(localStorage) to test if this is defined.
140
<button onClick="javascript:store();">Store base. </button>
<button onClick="javascript:retrieve();">Restore last base. </button> <button onClick="javascript:changebasetomarker();">Change base location to last marker. </button> <br/>
141
function store() { if (typeof(localStorage) == "undefined") { alert("Browser does not recognize HTML local storage."); } else { try { localStorage.setItem("baselat",blatlng.lat()); localStorage.setItem("baselng",blatlng.lng()); localStorage.setItem("basename",basename); catch(e) { alert("Error with use of local storage: "+e);} return false; }
142
function retrieve() { if (typeof(localStorage) == "undefined") { alert("Browser does not recognize HTML local storage."); } else { try { oldlat= localStorage.getItem("baselat"); oldlng = localStorage.getItem("baselng"); oldname = localStorage.getItem("basename"); if (oldlat==null) { alert("No base stored");} else {makemap(Number(oldlat),Number(oldlng)); basename = oldname; document.getElementById("header").innerHTML = "Base location is "+basename; } } catch(e) { alert("Error with use of local storage: "+e);} } return false; }
143
changes base to marker function changebasetomarker() {
if (lastmarker!="undefined") { makemap(lastmarker.lat(),lastmarker.lng()); basename = "marker"; }
144
Comments Error checking good!
Many GIS programs with common/similar features Need to determine where information goes my locations array kept information in my JavaScript
145
Plug for Book introduce application, mainly familiar games.
critical requirements HTML5 (CSS, JavaScript) features complete code: comments Many chapters involve sets of applications Introduction to programming NOTE: not encyclopedic on features
146
Applications (HTML5 features)
Favorite sites Dice game: drawing arcs & rectangles Bouncing ball: drawing, including gradient, form validation, timed events Cannonball & Slingshot: drawing lines & images, mouse events, rotation & translation, programmer-defined objects Memory polygons & pictures: drawing, mouse events (clicking on card), timing
147
Applications (HTML5 features)
Quiz: dynamically created HTML markup, mouse events on elements, video Mazes: mouse events, drawing, localStorage, radio buttons Rock, Paper, Scissors: drawing, audio Hangman: drawing lines and arcs (ovals), dynamic HTML markup Blackjack: key events, drawing images, footer
148
Conclusion Please email with comments on this tutorial and HTML5 for
professional use educational use Thank you
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.