Download - HTML5 - Pedro Rosa
O que é o HTML5 e porque é que me devo preocupar com isso?
Pedro Rosa
http://netponto.org36ª Reunião Presencial – Lisboa - 03/02/2013
HTML 5
CEO - RED DOGCTO – WorldAdCom
[email protected]://pt.linkedin.com/in/pedrobarraurosa/https://www.facebook.com/PedroRosa
Pedro Rosa
Agenda
Introduction To HTML5HTML5 Forms HTML5 Drag & Drop, Web Workers, Web Sockets HTML5 Canvas & SVGHTML5 Audio & VideoHTML5 Geo-location, Local Storage & Application CacheEverything Else HTML5Tools & Sites
Introduction To HTML5
Introducing HTML5 – State of the ArtThe HTML5 specification was adopted as the starting point of the work of the new HTML working group of the W3C in 2007.
2008 – First Public Working Draft2011 – Last Call2012 – Working Draft2014 – RecommendationHTML 5.1 – (Last Call -2014)(Working Draft – 2015)
Introducing HTML5 – Markup
HTML5 adds many new syntactic features. These include the new :
<video><audio><canvas> scalable vector graphics (SVG) content (that replaces the uses of generic <object> tags) MathML for mathematical formulas. Other new elements, such as <section>, <article>, <header> and <nav>.
Introducing HTML5 – Attributes ,DOM % API’s
GeolocationWeb SQL Database, a local SQL Database (no longer maintained).
The Indexed Database API, an indexed hierarchical key-value store (formerly WebSimpleDB).
HTML5 File API , handles file uploads and file manipulation.Directories and System. This API is intended to satisfy client-side- storage use cases not well served by databases.File Writer. An API for writing to files from web applications.Web Audio API, a high-level JavaScript API for processing and synthesizing audio in web applications.
HTML5 Differences From Previous Versions
New parsing rules: oriented towards flexible parsing and compatibility; not based on SGMLAbility to use inline SVG and MathML in text/htmlNew elements: article, aside, audio, bdi, canvas, command, data, datalist, details, embed, figcaption, figure, footer, header, hgroup, keygen, mark, meter, nav, output, progress, rp, rt, ruby, section, source, summary, time, track, video, wbrNew types of form controls: dates and times, email, url, search, number, range, tel, color[54]New attributes: charset (on meta), async (on script)Global attributes (that can be applied for every element): id, tabindex, hidden, data-* (custom data attributes)Deprecated elements will be dropped altogether: acronym, applet, basefont, big, center, dir, font, frame, frameset, isindex, noframes, strike, tt
HTML5 - Forms
HTML5 Forms - New Form Elements
HTML5 provides a series of tools to make developers life easier too:
New structural elements.New semantics for internationalization.New link relation types.New attributes.New form types.
Tag Description<datalist> Specifies a list of pre-defined options for input controls
<keygen> Defines a key-pair generator field (for forms)
<output> Defines the result of a calculation
HTML5 – New Elements
HTML5 provides a series of tools to make developers life easier too:
Tag Description<article> Defines an article<aside> Defines content aside from the page content<bdi> Isolates a part of text that might be formatted in a different direction from other
text outside it<command> Defines a command button that a user can invoke<details> Defines additional details that the user can view or hide<summary> Defines a visible heading for a <details> element<figure> Specifies self-contained content, like illustrations, diagrams, photos, code listings,
etc.<figcaption> Defines a caption for a <figure> element<footer> Defines a footer for a document or section<header> Defines a header for a document or section
HTML5 – New Elements
HTML5 provides a series of tools to make developers life easier too:
Tag Description<hgroup> Groups a set of <h1> to <h6> elements when a heading has multiple levels<mark> Defines marked/highlighted text<meter> Defines a scalar measurement within a known range (a gauge)<nav> Defines navigation links<progress> Represents the progress of a task<ruby> Defines a ruby annotation (for East Asian typography)<rt> Defines an explanation/pronunciation of characters (for East Asian typography)<rp> Defines what to show in browsers that do not support ruby annotations<section> Defines a section in a document<time> Defines a date/time<wbr> Defines a possible line-break
HTML5 Forms
HTML5 Forms
HTML5 Forms - <input>
AutoCompleteAutoFocusListMaxMinMultiplePaternPlaceholderStepRequired
FormFormActionFormEncTypeFormMethodFormTargetFormNoValidateHeight (px)Width (px)
New Atributes
HTML5 Forms
HTML5 Drag & Drop, Web Workers, Web Sockets
HTML5 Drag and Drop
Drag and drop is a part of the HTML5 standard.
<img draggable="true">
Make an Element Draggable
What to Drag - ondragstart and setData()
function drag(ev){ev.dataTransfer.setData("Text",ev.target.id);}
Where to Drop - ondragover
event.preventDefault()
Do the Drop - ondrop
function drop(ev){ev.preventDefault();var data=ev.dataTransfer.getData("Text");ev.target.appendChild(document.getElementById(data));}
HTML5 Drag and Drop
HTML5 Web Workers
JavaScript code running in a web page is single-threadedLong-running functions can cause the browser to become unresponsive
Web workers enable a web page to move code to a parallel execution environment, enabling the browser to remain responsive
Code in the web page communicates with the web worker by passing messages
Use Cases:Prefetching and/or caching data for later useCode syntax highlighting or other real-time text formattingSpell checkerAnalyzing video or audio dataBackground I/O or polling of webservicesProcessing large arrays or humungous JSON responsesImage filtering in <canvas>Updating many rows of a local web database
HTML5 Web Workers - Isolation
A web worker runs isolated from the web page and other web workers
It cannot access the document of the web pageIt cannot access data or JavaScript code in the web page
A web worker has access to a limit subset of JavaScript functionalityA web page communicates with a web worker by sending and receiving messages:
Send messages by using the postMessage() functionReceive messages by handling the message event
HTML5 Web Workers - Types
Dedicated web workers:Belong to a single pageCan only communicate with that pageStop when the page is closed
Shared web workers:Can be accessed by all pages in a web applicationCan communicate with any page in the web applicationStop when the web application finishes
HTML5 Web Workers - Dedicated
var worker = new Worker('task.js');worker.onmessage = function(event) { alert(event.data); };worker.postMessage('data');
self.onmessage = function(event) { // Do some work. self.postMessage("recv'd: " + event.data);};
task.js:
main.js:
HTML5 Web Workers - Shared
var worker = new SharedWorker("jsworker.js");
worker.port.addEventListener("message", function(e) {alert(e.data);}, false);worker.port.start();
// post a message to the shared web workerworker.port.postMessage("Alyssa");
pagescript.js:
var connections = 0; // count active connectionsself.addEventListener("connect", function (e) { var port = e.ports[0]; connections++; port.addEventListener("message", function (e) {port.postMessage("Hello " + e.data + " (port #" + connections +")");
}, false);port.start();
}, false);
jsworker.js:
HTML5 Web Workers
HTML5 Web Sockets
Full-duplex, bi-directional communication over the Web:
Both the server and client can send data at any time, or even at the same time. Only the data itself is sent, without the overhead of HTTP headers, dramatically reducing bandwidth.
var socket = new WebSocket('ws://RedDog.websocket.org/echo');socket.onopen = function(event) { socket.send('Hello, WebSocket');};socket.onmessage = function(event) { alert(event.data); }socket.onclose = function(event) { alert('closed'); }
HTML5 Web Sockets
The HTML5 Canvas & SVG
HTML5 Canvas
The HTML5 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics.Canvas has several methods for drawing paths, boxes, circles, characters, and adding images.<canvas id="myCanvas" width="200" height="100"style="border:1px solid #000000;"></canvas>
HTML5 Canvas
Drawing with Javascript.
To draw straight lines on a canvas.
<script>var c=document.getElementById("myCanvas");var ctx=c.getContext("2d");ctx.fillStyle="#FF0000";ctx.fillRect(0,0,150,75);</script>
ctx.moveTo(0,0);ctx.lineTo(300,150);ctx.stroke();
HTML5 Canvas
To draw a circle on a canvas.
To draw text on a canvas.
To draw an image on a canvas
ctx.beginPath();ctx.arc(95,50,40,0,2*Math.PI);ctx.stroke();
ctx.font="30px Arial";ctx.fillText("Hello World",10,50);ctx.strokeText("Hello World",100,500);
var img=document.getElementById("scream");ctx.drawImage(img,10,10);
The HTML5 Canvas
The HTML5 SVG
What is SVG?SVG stands for Scalable Vector GraphicsSVG is used to define vector-based graphics for the WebSVG defines the graphics in XML formatSVG graphics do NOT lose any quality if they are zoomed or resizedEvery element and every attribute in SVG files can be animatedSVG is a W3C recommendation
The HTML5 SVG
SVG Advantages:Advantages of using SVG over other image formats (like JPEG and GIF) are:SVG images can be created and edited with any text editorSVG images can be searched, indexed, scripted, and compressedSVG images are scalableSVG images can be printed with high quality at any resolutionSVG images are zoomable (and the image can be zoomed without degradation)
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190"> <polygon points="100,10 40,180 190,60 10,60 160,180" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;"></svg>
The HTML5 SVG
HTML5 - Comparison of Canvas and SVG
The table below shows some important differences between Canvas and SVG:
Canvas SVG
•Resolution dependent•No support for event handlers•Poor text rendering capabilities•You can save the resulting image as .png or .jpg•Well suited for graphic-intensive games
•Resolution independent•Support for event handlers•Best suited for applications with large rendering areas (Google Maps)•Slow rendering if complex (anything that uses the DOM a lot will be slow)•Not suited for game applications
HTML5 Audio & Video
HTML Multimedia Tags
<embed> Defines an embedded object<object> Defines an embedded object<param> Defines a parameter for an object<audio> Defines sound content<video> Defines a video or movie<source> Defines multiple media resources for media elements (<video> and <audio>)<track> Defines text tracks for media elements (<video> and <audio>)
HTML5 Audio
HTML5 provides a standard for playing audio files.
The control attribute adds audio controls, like play, pause, and volume.The <audio> element allows multiple <source> elements. <source> elements can link to different audio files.
<audio controls> <source src="horse.ogg" type="audio/ogg"> <source src="horse.mp3" type="audio/mpeg">Your browser does not support the audio element.</audio>
HTML5 Video
Videos can be played in HTML by many different methods.<video width="320" height="240" controls> <source src="movie.mp4" type="video/mp4"> <source src="movie.ogg" type="video/ogg"> <source src="movie.webm" type="video/webm"> <object data="movie.mp4" width="320" height="240"> <embed src="movie.swf" width="320" height="240"> </object> </video>
http://dev.opera.com/articles/view/custom-html5-video-player-with-css3-and-jquery/
HTML5 Audio & Video
HTML5 Geo-location, Forms, Local Storage & Application Cache
HTML5 Geolocation
HTML5 Geolocation is used to locate a user's positionSince this can compromise user privacy, the position is not available unless the user approves it.<script>var x=document.getElementById("demo");function getLocation(){ if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(showPosition); }else{ x.innerHTML="Geolocation is not supported by this browser."; }}function showPosition(position){ x.innerHTML="Latitude: "+position.coords.latitude+ "<br>Longitude:"+position.coords.longitude; }</script>
HTML5 Geo-location
HTML5 - Storage
With HTML5, web pages can store data locally within the user's browser.
HTML5 - Storage
Web Storage simply provides a key-value mapping, e.g. localStorage["name"] = username;. Web SQL Database gives you all the power - and effort - of a structured SQL relational database.Indexed Database is somewhere in between Web Storage and Web SQL Database.File Access is an API for reading file content in JavaScript. Given a set of files the user has added to a "file" input element, you can read the content of the file or reference it as a URL
HTML5 Local Storage - Cookies
Cookies:Were designed to implement session tokensAre sent to the server on every page requestAre small files of limited size, up to 4 KBAre open to abuseHave no synchronization or concurrency mechanism
Cookies were not designed for general-purpose data storage
HTML5 Local Storage & Session Storage
There are two new objects for storing data on the client:
localStorage - stores data with no expiration datesessionStorage - stores data for one session
Before using web storage, check browser support for localStorage and sessionStorage:
HTML5 - The localStorage Object
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
if (localStorage.clickcount) { localStorage.clickcount=Number(localStorage.clickcount)+1; }else { localStorage.clickcount=1; }document.getElementById("result").innerHTML="You have clicked the button " + localStorage.clickcount + " time(s).";
HTML5 - The sessionStorage Object
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the browser window.
if (sessionStorage.clickcount) { sessionStorage.clickcount=Number(sessionStorage.clickcount)+1; }else { sessionStorage.clickcount=1; }document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";
Local Storage & Session Storage
HTML5 - IndexedDB
IndexedDB is an Object Store. It is not the same as a Relational Database, which has tables, with collections rows and columns. In a traditional relational data store we would have a table of "todo" items that store a collection of the users todo data in rows.IndexedDB differs in that you create an Object Store for a type of data and simply persist Javascript Objects to that store. Query against an index which produces a cursor that you use to iterate across the result set.
HTML5 – IndexedDB – Why?
On November 18, 2010, the W3C announced that Web SQL database is a deprecated specification. This is a recommendation for web developers to no longer use the technology as effectively the spec will receive no new updates and browser vendors aren't encouraged to support this technology.
Many major browsers including Chrome, Safari, Opera and nearly all Webkit based mobile devices support WebSQL and will likely maintain support for the foreseeable future.
HTML5 - Web SQL Database
Structured database with all the functionality - and complexity - of a typical SQL-powered relational database. Indexed Database sits somewhere between the two. It has free-form key-value pairs, like Web Storage, but also the capability to index fields from those values, so searching is much faster.
Deprecated. Will not be supported on IE or Firefox, and will probably be phased out from the other browsers at some stage.
INDEXEDDB
HTML 5 - Application cache
HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection.Application cache gives an application three advantages:
Offline browsing - users can use the application when they're offlineSpeed - cached resources load fasterReduced server load - the browser will only download updated/changed resources from the server
HTML5 – Application Cache
There are three different sections in a manifest file:
CACHEA list of explicit URLs to request and store
FALLBACKWhat to do when an offline user attempts to access an uncached file
NETWORKWhich resources are available only while online
HTML5 Application Cache
Everything Else HTML5
HTML5 - Microdata
Microdata consists of a group of name-value pairs. The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements.
HTML5 – Microdata<section> Hello, my name is John Doe, I am a graduate research assistant atthe University of Dreams.My friends call me Johnny. You can visit my homepage at <a href="http://www.JohnnyD.com">www.JohnnyD.com</a>.I live at 1234 Peach Drive, Warner Robins, Georgia.</section>
<section itemscope itemtype="http://schema.org/Person"> Hello, my name is <span itemprop="name">John Doe</span>, I am a <span itemprop="jobTitle">graduate research assistant</span> at the <span itemprop="affiliation">University of Dreams</span>. My friends call me <span itemprop="additionalName">Johnny</span>. You can visit my homepage at <a href="http://www.JohnnyD.com" itemprop="url">www.JohnnyD.com</a>. <section itemprop="address" itemscope itemtype="http://schema.org/PostalAddress"> I live at <span itemprop="streetAddress">1234 Peach Drive</span>, <span itemprop="addressLocality">Warner Robins</span>, <span itemprop="addressRegion">Georgia</span>. </section></section>
HTML5 – CSS3
Tools & Sites