CS计算机代考程序代写 Java javascript More HTLM5 Features

More HTLM5 Features
2020/21 COMP3322 Modern Technologies on WWW

Content
• HTML5 Geolocation
• HTML5 Canvas
• HTML5 Audio & Video • HTML5 Drag & Drop
• HTML5 Local Storage
2

HTML5 Geolocation API
• The HTML Geolocation API is used for getting the geographical position of a user.
• Since this can compromise privacy, the position is not available unless the user approves it.
Method / Property
Description
navigator.geolocation
The geolocation interface implemented by the Navigator object
getCurrentPosition()
Determines the device’s current location and gives back a Position object with the data.
watchPosition()
Returns the current position of the user and continues to return updated position as the user moves.
clearWatch()
Removes the particular handler previously installed using watchPosition().
3

getCurrentPosition()
• success() – A callback function that takes the return Position object as its sole input parameter.
• error() – An optional callback function that takes a PositionError object as its sole input parameter.
• Position object:
• coords property – Returns a Coordinates object defining the current location. • coords.latitude-Thelatitudeasadecimalnumber.
• coords.longitude-Thelongitudeasadecimalnumber.
• timestamp property – Returns a DOMTimeStamp representing the time at which the location was retrieved.
https://i7.cs.hku.hk/~atctam/c3322/HTML5/getloc.html
navigator.geolocation.getCurrentPosition(success, error)
4

Working with Map API
• We can use the information obtained from the Geolocation as an input to the Map API.
• There are various Map APIs for us to display map on our web pages. • Google Maps JavaScript API
• Bing Maps • MapBox
• Most of the Map APIs are paid services with limited free trial for some duration or usage volume
• To use these APIs, we must get an API key in order to request the services.
• We are using a free Map API – OpenLayers
5

https://i7.cs.hku.hk/~atctam/c3322/HTML5/location.html
Load the OpenLayers Map
1. Define a place in your web page for the map; use CSS to set the size of your map.
2. Load the Map API to your web page using the
3. Use JavaScript to create a simple map
var map = new ol.Map({ target: 'map',
layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }) ], view: new ol.View({
center: ol.proj.fromLonLat([114.2, 22.28]), zoom: 11
}) });
6





7



Get geolocation info
navigator.geolocation.getCurrentPosition(success, error);
10

HTML5 Canvas
• The element is a two-dimension drawing surface that uses JavaScript coding to perform drawing:
• forexample:creatinglines,shapes,fills,text,animations,andsoon.
• all using the native browser behavior and without proprietary plug-ins like Flash.
• Add a canvas space with the element and specify the dimension with the width and height attributes.
• By default, no border and no content.
• Forbrowsersthatdon’tsupportthecanvaselement,providesomefallback
content inside the tags.

The browser does not support HTML5 canvas.

Fallback content
11

HTML5 Canvas
• To display something, a script first needs to access the rendering context and draw on it.
• Example to draw the rectangles: Obtain the rendering context
and its drawing functions
Drawing
Define the space




12

Rendering Contexts
• The getContext() method returns an object that provides methods and properties for drawing on the canvas.
• There are currently two widely supported contexts: "2d" for 2-D graphics and "webgl" for 3-D graphics through the OpenGL interface.
• Only "2d" will be discussed.
canvas.getContext(contextType);
13

Drawing
• Canvas grid • Define a path and draw lines/curves/arcs
• Drawing Rectangle
Method Description
beginPath() Starts a path drawing
closePath() Ends a path drawing
moveTo(x1,y1) Moves to location (x1,y1) without drawing
lineTo(x2,y2) Sets the end point of the line to (x2,y2)
arc(x,y,r,s,e,d) Draws a circle or arc path, centre at (x,y) with radius r, starting the arc at angle s (in
radians), and ending at angle e. [Default of d is false which is clockwise direction]
quadraticCurveTo() Creates a quadratic Bézier curve path
bezierCurveTo() Creates a cubic Bézier curve path
stroke() Draws the path
fill() Fills the current drawing
Method Description
fillRect(x,y,w,h) Draws a rectangle and fill with color (default: black)
starting at coordinate: (x,y) with width w and height h
strokeRect(x,y,w,h) Draws a rectangular outline.
clearRect(x,y,w,h) Clears the rectangle defined by (x,y) and size (w,h)
14

Text and Color
Method / Property Description
font Sets or returns the current font properties for text content (same syntax as the CSS font property)
textAlign Sets or returns the current alignment (start | end | center | left | right) for the text content. The alignment is relative to the x
value of the fillText() method.
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_c anvas_textalign
fillText(text,x,y) Draws and fills text on the canvas
strokeText(text,x,y) Draws text on the canvas (no fill)
fillStyle Sets or returns the color, gradient, or pattern used to fill the drawing
strokeStyle Sets or returns the color, gradient, or pattern used for strokes
createLinearGradient() Creates a linear gradient (to use on canvas content)
createRadialGradient() Creates a radial/circular gradient (to use on canvas content)
15


Your browser does not support the canvas element.

Example

17

Images
• Using the drawImage() method, we can take an image object and draw it onto a canvas.
• The image can be loaded from a server or even extracted from a canvas. • Importing images into a canvas involves two steps:
• Get a reference to an HTMLImageElement object or to another canvas element as a source.
• It is also possible to use images by providing a URL.
• Draw the image on the canvas using the drawImage() function.
18

Example

Your browser does not support the canvas element.


19

Example


Your browser does not support the canvas element.


context.drawImage(img,x,y,width,height);
20

context.drawImage(img,sx,sy,swidth,sheight, x,y,width,height);
Example

21

HTML5 Audio
• The

The Medallion Calls - Pirates of the Carribean


Attribute Description
autoplay Starts playing as soon as the audio is ready.
controls Specifies that audio controls should be displayed.
loop Specifies that the audio will be repeated.
muted The audio output should be muted
controls
Fallback content
22

HTML5 Video
• Like the audio embedding, the HTML5

Example






poster="Jasper.jpg"
24

HTML5 Audio and Video
• HTML5 provides DOM methods, properties and events for us to manipulate the audio and video elements using JavaScript.
• Methods: play(), load(), pause() & addTextTrack()
• Properties: currentTime, duration, ended, readyState, volume, etc. • Events: play, pause, ended, canplay, waiting, playing, etc.
25

HTML5 Drag and Drop
• HTML Drag and Drop interfaces enable applications to use drag and drop features.
• In HTML5, any element can be draggable.
• Basic steps:
• A draggable element is selected with a mouse.
• Drag the element to a droppable element.
• Release the mouse button to drop the element.
• During the operations, several events are fired. Actions are installed in this event handlers to implement this drag and drop feature.
26

Over a droppable element
Drag Events
drag dragover drop
Release mouse button
Event On Event Description Handler
drag ondrag Fired when an element is being dragged.
dragend ondragend Fired at the source when a drag operation is being ended.
dragenter ondragenter Fired when a dragged element enters a valid drop target.
dragleave ondragleave Fired when a dragged element leaves a valid drop target.
dragover ondragover
Fired when an element is being dragged over a valid drop target.
dragstart ondragstart Fired when the user starts dragging an element.
drop ondrop Fired when an element is dropped on a valid drop target.
27

A Draggable Element
• To make a HTML element draggable, do this: • Set the draggable attribute to true.
• Add a listener for the dragstart event.
• Set the drag data within the listener defined above.
function drag(event) { event.dataTransfer.setData("text/plain", event.target.id);
}
• All drag events have a property called dataTransfer which holds the drag data.
• When the drag begins, store the type and a DOMString (presenting the data) to the dataTransfer property of the drag event object.

28

A Droppable Element
• By default, the browser prevents anything from happening when dropping something onto the HTML element.
• To make the HTML element as a droppable zone, do this:
• Settheelement’sondragoverandondropattributespointtothecorresponding
event handlers.
• The dragover event handler has to override the non-droppable
behavior by calling the preventDefault() method.
• The drop event handler has to
• Overridethedefaultactiononthedroppedobject. • Getthedraggedelement.
• Appendtheelementintothedropelement.
function allowDrop(event) { event.preventDefault();
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("text/plain"); event.target.appendChild(document.getElementById(data));
}
29

Dragging the image to copy it into the above element.
br>

Example

30

HTML5 Local Storage
• Web storage provides a way for your web applications to store data locally within the user’s browser.
• Prior to HTML5, Web applications use cookies to keep state information.
• Cookies are included with every HTTP request. • Cookies are limited to about 4 KB of data.
• With web storage, storage limit is larger than that of cookies with up to 5 MB of data per domain and information is never transferred to the server.
31

Types of Web Storage
• Two main web storage types:
• Local storage
• The data in local storage would persist even when the browser is closed and reopened.
• Each site has its own separate storage area. The data is available to all scripts loaded from pages from the same site.
• Examples: a page visit count, user-authored documents, etc. • Session storage
• Only stores data for one session; will be deleted from the browser once the browser/tab is closed.
• Stored data will be accessible to any page from the same site opened in that window/tab.
32

Usage (for both localStorage and sessionStorage)
• Check Storage support in browser:
• To clear the all items in localStorage:
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
}
• Store, retrieve & remove a localStorage:
• To lookup a key name, use
https://www.w3schools.com/jsref/tryit.asp?fil ename=tryjsref_storage_loop
localStorage.clear();
// Store
localStorage.setItem("lastname", "Smith"); localStorage.firstname = "John";
// Retrieve localStorage.getItem("lastname"); localStorage.firstname
// Remove
localStorage.removeItem("lastname");
localStorage.key(index);
33

Example

Refresh the page to increase number of hits.

Close the window and open it again and check the result.


34

References
• https://www.w3schools.com/graphics/canvas_intro.asp
• https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial
• https://developer.mozilla.org/en- US/docs/Learn/HTML/Multimedia_and_embedding/Video_and_audio_content
• https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API
• https://developer.mozilla.org/en-
US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
• https://www.tutorialrepublic.com/html-tutorial/html5-web-storage.php
• https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API
• https://openlayers.org/en/latest/doc/quickstart.html
35