1.04k likes | 1.17k Views
Pro HTML5 Programming Powerful APIs for Richer Internet Application Development. Chap 1. overview of html5. History of HTML5. HTML was first published as an Internet draft in 1993.
E N D
Pro HTML5 ProgrammingPowerful APIs for Richer Internet Application Development
History of HTML5 • HTML was first published as an Internet draft in 1993. • Version 2.0, 3.2, 4.0 occurred in the same year, and finally 4.01 in 1999, W3C assumed control of the specification. • Then, HTML was considered a dead-end; web standards shifted to XML and XHTML. • HTML5 specification was created by Web Hypertext Application Working Group (WHATWG) in 2004. • W3C became involved with HTML again in 2006 and published first working draft in 2008, and XHTML 2 stopped in 2009. • Today, HTML5 solves very practical problems, browser vendors are feverishly implementing its new features, even though the specification has not been completely locked down.
Myth of 2022 • HTML5 spec. is a working draft today (not final). • 2012: candidate recommendation. (HTML5 will be complete ) • 2022: proposed recommendation. • IE6 does not support many of new features. • Microsoft promises to design that browser with increased HTML5 support.
Who is developing HTML5 • Web Hypertext Application Technology Working Group (WHATWG) • Founded in 2004 • Vendors: Apple, Mozilla, Google, Opera • World Wide Web Consortium (W3C) • Internet Engineering Task Force (IETF) • HTML5 defines a new WebSocket API that relies on a new WebSocket protocol.
Characteristics of HTML5 • Compatibility • Utility - Separation of Presentation (CSS) and Content (HTML) • Most of presentational features of earlier versions of HTML are no longer supported (but will still work!). • Shortages of older versions of HTML • Poor accessibility • Unnecessary complexity (Harder to read code) • Large document size – slower loading pages • Interoperability - Simplify wherever possible • Native browser ability instead of complex JavaScript code • A new, simplified DOCTYPE and simplified character set declaration • Powerful yet simple HTML5 APIs • Universal access: • Accessibility • Media independence • Support for all world languages: Ex: <ruby> supports Ruby annotation
A Plugin – Free Paradigm • Present problem of plugin • Cannot always be installed • Can be disabled or blocked (Ex: iPad does not ship with a Flash plugin) • Often blocked in controlled corporate environments • Users disable because of unwelcome advertising • A separate attack vector • Difficult to integrate with the rest of HTML document
HTML5 Features • Scalable Vector Graphics (SVG) • WebSocketAPI and protocol • Web origin concept • Web Storage • Web SQL database • Web Workers • XMLHTTPRequest Level 2 • Canvas (2D or 3D) • Channel messaging • Cross-document messaging • Geolocation • MathML • Microdata • Server-Sent Event
New DOCTYE and Character Set • DOCTYPE • <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> • <!DOCTYPE html> • Character set • <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> • <meta charset="utf-8">
New and Deprecated Elements Deprecated Elements: Elements perform inline styling in favor of using CSS, Ex: big, center, font
Semantic Markup • The sectioning content type is useful for search engine. • New sectioning HTML5 elements
HTML5 Tag - <link> • <link> • Define the relationship between a document and an external resource • Placed at <head> • Attributes • Example: <link rel=“stylesheet” href=“html5.css”>
CSS – webkit/moz • webkit and moz mean they are not W3C standard • webkit • Supported by Safari and Chrome • -webkit-box-shadow: 2px 2px 20px #888; (Shadow effect) • -webkit-transform: rotate(-45deg); (Rotate effect) • -webkit-transform: scale(0.5);(Change size) • -webkit-border-radius: 10px; • moz • Supported by Mozilla • -moz-box-shadow: 2px 2px 20px #888; (Shadow effect) • -moz-transform: rotate(-45deg); (Rotate effect) Excerise: Listing 1-1, 1-2
Simplifying Section – Selectors API HTML4 HTML5 HTML5 Excerise: Listing 1-3
Windows.JSON AND DOM LEVEL 3 • JSON • A relatively new and increasing popular way to represent data • Data is represented as objects • In older browsers, a JavaScript library (http://json.org) is necessary. Parsing and serializing are not always fast enough • Newer browsers have a native implementation of JSON • DOM Level 3 • Most browsers support standard APIs for events and elements, Internet Explorer differs. • IE9 will support DOM level 2 and 3 features.
What is canvas • Dynamically generate and render graphics, charts, images and animations • SVG (Scalable Vector Graphics) vs. Canvas • Bitmap canvas • Images drawn on a canvas are final and not be resized • Objects drawn on a canvas are not part of the page’s DOM or any namespace • SVG images can be scaled seamlessly at different resolutions and allow hit detection • HTML5 Canvas API • It performs well because it does not have to store objects for every primitive it draws • Relatively easy to implement the Canvas API
Canvas • Element: <canvas></canvas> • Coordinates:
Checking browser support try { document.createElement("canvas").getContext("2d"); document.getElementById("support").innerHTML = "HTML5 Canvas is supported in your browser."; } catch (e) { document.getElementById("support").innerHTML = "HTML5 Canvas is not supported in your browser."; }
Canvas, Draw line • A basic canvas with solid border • <canvas id=“canvas" height="800" width="1000" style="border: 3px solid"></canvas> • Get the canvas element and its context var canvas = document.getElementById('canvas'); varcontext = canvas.getContext('2d'); • Draw line • Prepare graph context.beginPath(); context.moveTo(70, 140); context.lineTo(140, 70); • Stroke graph onto the canvas • context.stroke(); Excerise
translation • Get the canvas element and its context • Save the current drawing state context.save(); • Move to new coordinate, ex: (50, 100) context.translate(50, 100); • Draw line • Restore the old drawing state context.restore(); Excerise
Path context.beginPath(); context.moveTo(-25, -50); context.lineTo(-10, -80); context.lineTo(-20, -80); context.lineTo(-5, -110; context.lineTo(-15, -110); context.lineTo(0, -140); context.lineTo(15, -110); context.lineTo(5, -110); context.lineTo(20, -80); context.lineTo(10, -80); context.lineTo(25, -50); ontext.closePath();
Stroke style • Line width • context.lineWidth = 4; • Corner style at path joins (round:圓角, bevel:斜角, miter) • context.lineJoin = 'round'; • Line style at endpoints (round, square, butt:預設值) • Context.lineCap = ‘square'; • Stroke style • Change color • context.strokeStyle= '#663300'; • Background pattern • Fill Style • Change color • context.fillStyle= '#339900'; • Background pattern • Fill the region inside all the closed paths • context.fill(); • Fill rectangular content • context.fillRect(x, y, w, h); //ex: context.fillRect(-5, -50, 10, 50);
Quadratic Curve • Starting Point: current location • context.quadraticCurveTo(ControlPointX, ControlPointY, EndPointX, EndPointY); • Example: • context.save(); • context.translate(-10, 350); • cucontext.moveTo(0, 0); • context.quadraticCurveTo(170, -50, 260, -190); • context.quadraticCurveTo(310, -250, 410, -250); • context.lineWidth = 20; • context.strokeStyle= '#663300'; • ontext.stroke(); • context.restore();
Image • Load image varimg = new Image(); img.src = “bark.jpg”; • Confirm the image is loaded img.onload = function(){ //Draw image onto canvas } • Draw image onto canvas • context.drawImage(image, dx, dy) • context.drawImage(image, dx, dy, dw, dh) • context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) • Example • var bark = new Image(); • bark.src= "bark.jpg"; • bark.onload= function(){ • context.drawImage(bark, -5, -50, 10, 50); • context.stroke(); • context.restore(); • }
GRADIENT • Linear Gradient(漸層) • Usage • context.createLinearGradient(x0, y0, x1, y1) • x0, y0 - Line start • x1, y1 - Line end • gradient.addColorStop(offset, color) • offset - From 0.0 to 1.0 • color - Use rgba() or HEX • Example • vartrunkGradient = context.createLinearGradient(-5, -50, 5, -50); • trunkGradient.addColorStop(0, '#663300'); • trunkGradient.addColorStop(0.4, '#996600'); • trunkGradient.addColorStop(1, '#552200'); • context.fillStyle= trunkGradient; • context.fillRect(-5, -50, 10, 50); • Radical Gradient • Usage • Context.createRadicalGradient(x0, y0, r0, x1, y1, r1) • x0, y0, r0 – First circle center at (x0, y0) with radius r0 • x1, y1, r1 – Second circle center at (x1, y1) with radius r1
Background Pattern • Usage • context.createPattern(image, repeat) • repeat - repeat, repeat-x, repeat-y, no-repeat • Example vargravel = new Image(); gravel.src= "gravel.jpg"; context.save(); context.translate(-10, 390); gravel.onload= function(){ context.beginPath(); context.moveTo(0, 0); context.quadraticCurveTo(170, -50, 260, -190); context.quadraticCurveTo(310, -250, 410, -250); context.lineWidth = 20; context.strokeStyle = context.createPattern(gravel, 'repeat'); context.stroke(); context.restore(); }
Scale • Usage • context.scale(rx, ry); • rx – width scale ratio • ry – height scale ratio • Example • varcanvas = document.getElementById('canvas'); • varcontext = canvas.getContext('2d'); • context.save(); • context.translate(260, 500); • context.scale(2, 2); • drawTree(context); • context.restore();
Rotate • Usage • context.rotate(angle) • angel can be express with Math.PI/180 * degree • Example • var canvas = document.getElementById('canvas'); • var context = canvas.getContext('2d'); • context.save(); • context.translate(260, 500); • context.rotate(Math.PI/180 * 40); • drawTree(context); • context.restore();
Transform • Context.transform(rx, sy, sx, ry, dx, dy) • rx – width scale ratio • ry – height scale ratio • sy– vertical shear • sx– horizontal shear • Example • var canvas = document.getElementById('canvas'); • varcontext = canvas.getContext('2d'); • context.save(); • context.translate(130, 250); • context.transform(1, 0, -0.5, 1, 0, 0); • context.scale(1, 0.6); • context.fillStyle= 'rgb(0, 0, 0, 0.2)'; • context.fillRect(-5, -50, 10, 50); • createCanopyPath(context); • context.fill(); • context.restore();
Canvas text • Usage • context.fillText(text, x, y, maxwidth) • context.strokeText(text, x, y, maxwidth) • Property • context.font = Font String • context.textAlign = start, end, left, right, center • context.textBaseLine = top, middle, bottom, … • Example • context.save(); • context.font= '60px 標楷體'; • context.fillStyle= '#996600'; • context.textAlign= 'center'; • context.fillText('快樂圖畫', 200, 60, 400); • context.restore();
Shadows • Usage • shadowColor – Any CSS Color • shadowOffsetX – Pixel Count • shadowOffsetY – Pixel Count • Shadowblur – Gaussian blur • Example • context.shadowColor= 'rgba(0, 0, 0, 0.2)'; • context.shadowOffsetX= 15; • context.shadowOffsetY= -10; • context.shadowBlur= 2; • context.font= '60px 標楷體'; • context.fillStyle= '#996600'; • context.textAlign= 'center'; • context.fillText('快樂圖畫', 200, 60, 400);
Video Container • An audio or video file is really just a container file, similar to a ZIP archive file that contains a number of files. • Some of the popular video container formats include the following: • Audio Video Interleave (.avi) • Flash Video (.flv) • MPEG 4 (.mp4) • Matroska(.mkv) • Ogg(.ogv)
Audio and Video Codecs • Audio and video coders/decoders (codecs) are algorithms used to encode and decode a particular audio or video stream so that they can be played back. • Some example audio codecs are the following: • AAC • MPEG-3 • OggVorbis • Example video codecs are the following: • H.264 • VP8 • OggTheora
Restrictions • Streaming audio and video. • That is, there is currently no standard for bitrate switching in HTML5 video • Media is restricted by HTTP cross-origin resource sharing. • Full-screen video is not scriptable • Because it could be considered a security violation to let a scriptable element take over the full screen. • Accessibility for audio and video elements is not fully specified yet. • Work is underway on a specification called WebSRT for subtitle support based on the popular SRT format.
Browser Support • Browser support for HTML5 Video • Checking for Browser Support • JavaScript • varhasVideo = !!(document.createElement('video').canPlayType); • HTML Fallback content • <video src="video.ogg" controls> • Your browser does not support HTML5 video. • </video>
HTML USAGE • Audio • <audio controls> • <source src="johann_sebastian_bach_air.ogg"> • <source src="johann_sebastian_bach_air.mp3"> • An audio clip from Johann Sebastian Bach. • </audio> • Video • <video id="movies“ autoplayautobuffer="true" width="400px" height="300px"> • <source src="Intermission-Walk-in.ogv"> • <source src="Intermission-Walk-in_512kb.mp4"> • </video>
Taking Control • Common control functions
WORKING WITH Audio • <audio id="clickSound"> • <source src="johann_sebastian_bach_air.ogg"> • <source src="johann_sebastian_bach_air.mp3"> • </audio> • <button id="toggle" onclick="toggleSound()">Play</button> • <script type="text/javascript"> • function toggleSound(){ • var music = document.getElementById("clickSound"); • vartoggle = document.getElementById("toggle"); • if (music.paused) { //檢查是否已暫停 • music.play(); • toggle.innerHTML = "Pause"; • } else { • music.pause(); • toggle.innerHTML ="Play"; • } • } • </script>
About Location Information • You can request users to share their location and, if they agree, you can providethem with instructions on how to get to a nearby store to pick up a new pair of shoes at a discountedrate. • You request a position and, if the useragrees, the browser returns location information. • The position is provided to the browser by the underlying device (for example, a laptop or a mobile phone) on which the HTML5 Geolocation–enabledbrowser is running. • IPAddress • Global Positioning System (GPS) • Wi-Fi with MAC addresses from RFID, Wi-Fi, and Bluetooth • GSM or CDMA cell phone IDs
Arachitecture & Privacy • The browser intercepts and requests user permission at step 2.
Browser Support • Browser support for HTML5 Geolocation
Checking for Browser Support • if(navigator.geolocation) { • document.getElementById("support").innerHTML = "HTML5 Geolocation supported."; • } else { • document.getElementById("support").innerHTML = "HTML5 Geolocation is not supported in your browser."; • }
Positions requests • Theres are two type of position requests • One-shot position request • Repeated position updates
One-Shot Position Requests • Usage • void getCurrentPosition(in PositionCallbacksuccessCallback, • in optional PositionErrorCallbackerrorCallback, • in optional PositionOptions options); • Example • navigator.geolocation.getCurrentPosition(updateLocation, handleLocationError, {timeout:10000}); • updateLocationis a PositionCallback function will implement later • handleLocationErroris a PositionErrorCallback function will implement later