70
HTML5 Quick Start Jeff Prosis e Cofounder Wintellect

HTML5 Quick Start

Embed Size (px)

DESCRIPTION

More info on http://www.techdays.be

Citation preview

Page 1: HTML5 Quick Start

HTML5 Quick Start Jeff

ProsiseCofounderWintellect

Page 2: HTML5 Quick Start

HTML5Successor to HTML 4.01Not one specification, but a set of related specificationsDriven by standards committees and browser vendors

Adds many new features to the languageCanvas API, Web storage, geolocation, and moreEnriched semantic content and standard parsing rulesStandardized DOM and DOM APIs

HTML5 + JavaScript = Application platform

Page 3: HTML5 Quick Start

HTML5 FeaturesHTML5 Core

Geolocation

Audio and Video

Canvas

Web Storage

Indexed DB

Web Workers

XHR2

WebSockets

Server-SentEvents

File APIs

History &Navigation

Offline Applications

Drag and Drop

Web Notification

s

Media Capture

Clipboard

Network Information

Audio Processing

Touch

Contacts &Calendar

Messaging API

Device Orientation

Battery StatusForms

Page 4: HTML5 Quick Start

Detecting Features Manually// Check for canvas support

if (document.createElement("canvas").getContext) {

// This browser supports the canvas API

}

// Check for local storage support

if ("localStorage" in window && window["localStorage"] !== null) {

// This browser supports local storage

}

Page 5: HTML5 Quick Start

Detecting Features with Modernizr<script src="modernizr-1.7.min.js"></script>

// Check for canvas support

if (Modernizr.canvas) {

// This browser supports the canvas API

}

// Check for local storage support

if (Modernizr.localstorage) {

// This browser supports local storage

}

Page 6: HTML5 Quick Start

DemoBrowser Support for HTML5

Page 7: HTML5 Quick Start

GeolocationAPI for determining user's locationLatitude, longitude, altitude, speed, and course

NavigatorGeolocation object provides core APIGPS (most accurate), WiFi (WPS), and cell towersAccessed through navigator.geolocation

Current status: working draftIE9+

Chrome5+

Firefox3.5+

Opera10.6+

Safari5+

Page 8: HTML5 Quick Start

Getting the Current Positionnavigator.geolocation.getCurrentPosition(onPositionReady);

...

// Called one time

function onPositionReady(position) {

var latitude = position.coords.latitude;

var longitude = position.coords.longitude;

var altitude = position.coords.altitude;

var accuracy = position.coords.accuracy;

var altitudeAccuracy = position.coords.altitudeAccuracy;

var heading = position.coords.heading;

var speed = position.coords.speed;

var timestamp = position.timestamp;

}

Page 9: HTML5 Quick Start

Handling Errorsnavigator.geolocation.getCurrentPosition(onPositionReady, onError);

...

function onError(err) {

switch (err.code) {

case PositionError.PERMISSION_DENIED:

// User denied the request

break;

case PositionError.POSITION_UNAVAILABLE:

// Location data isn't available

break;

case PositionError.TIMEOUT:

// The location request timed out

break;

}

}

Page 10: HTML5 Quick Start

Requesting High Accuracynavigator.geolocation.getCurrentPosition(onPositionReady,

onError, { enableHighAccuracy: true });

Page 11: HTML5 Quick Start

Specifying a Timeout Intervalnavigator.geolocation.getCurrentPosition(onPositionReady,

onError, { timeout: 10000 });

Page 12: HTML5 Quick Start

Watching the Current Positionnavigator.geolocation.watchCurrentPosition(onPositionReady);

...

// Called every time the user's location changes

function onPositionReady(position) {

var latitude = position.coords.latitude;

var longitude = position.coords.longitude;

var altitude = position.coords.altitude;

var accuracy = position.coords.accuracy;

var altitudeAccuracy = position.coords.altitudeAccuracy;

var heading = position.coords.heading;

var speed = position.coords.speed;

var timestamp = position.timestamp;

}

Page 13: HTML5 Quick Start

Canceling a Watchvar watchid =

navigator.geolocation.watchCurrentPosition(onPositionReady);

.

.

.

navigator.clearWatch(watchid);

Page 14: HTML5 Quick Start

DemoGeolocation

Page 15: HTML5 Quick Start

Audio and VideoHTML5 makes media content a first-class citizenPlug-ins no longer required to play audio and video

Encapsulated in <audio> and <video> elementsCodec support fragmented but manageableNo DRM or streaming support

Current status: working draftIE9+

Chrome4+

Firefox3.5+

Opera10.5+

Safari4+

Page 16: HTML5 Quick Start

HTML 4 Video<object width="960" height="750">

<param name="movie" value="http://www.youtube.com/v/vptOqcppAzA..."></param>

<param name="allowFullScreen" value="true"></param>

<param name="allowscriptaccess" value="always"></param>

<embed

src=http://www.youtube.com/v/vptOqcppAzA..."

type="application/x-shockwave-flash"

allowscriptaccess="always"

allowfullscreen="true"

width="960" height="750">

</embed>

</object>

Page 17: HTML5 Quick Start

HTML5 Video<video src="f-16.mp4" controls />

Internet Explorer 9 Chrome 10

Page 18: HTML5 Quick Start

Browsers and Video CodecsNo single format is supported by all browsersFor maximum reach, perform multiple sourcingIE – MP4Chrome – MP4, Ogg, and WebMFirefox – Ogg and WebMOpera - OggSafari – MP4iPhone and iPad - MP4 (H.264 baseline profile + AAC low-complexity profile)Android - MP4 (H.264 baseline profile + AAC low-complexity profile)

Page 19: HTML5 Quick Start

Multiple Sourcing<video controls>

<source src="f-16.mp4" type="video/mp4" />

<source src="f-16.webm" type="video/webm" />

<source src="f-16.ogv" type="video/ogg" />

</video>

Page 20: HTML5 Quick Start

Specifying Codecs<video controls>

<source src="f-16.mp4" type="video/mp4" codecs="avc1.42E01E, mp4a.40.2" />

<source src="f-16.webm" type="video/webm" codecs="vp8, vorbis" />

<source src="f-16.ogv" type="video/ogg" codecs="theora, vorbis" />

</video>

Page 21: HTML5 Quick Start

Providing Down-Level Support<video controls>

<source src="f-16.mp4" type="video/mp4" />

<source src="f-16.webm" type="video/webm" />

<source src="f-16.ogv" type="video/ogg" />

<embed

src=http://www.youtube.com/v/vptOqcppAzA..."

type="application/x-shockwave-flash"

allowscriptaccess="always"

allowfullscreen="true"

width="960" height="750">

</embed>

</video>

Page 22: HTML5 Quick Start

DemoHTML5 Video

Page 23: HTML5 Quick Start

The <canvas> ElementPixel-addressable drawing surface for rendering text, graphics, and other visual elementsgetContext method retrieves rendering contexttoDataUrl method renders contents to data URL

CanvasRenderingContext2d methods and properties provide immediate-mode drawing API

IE9+

Chrome4+

Firefox2+

Opera9+

Safari3.1

Page 24: HTML5 Quick Start

Getting a Rendering Context// HTML

<canvas id="output" width="400" height="200"></canvas>

// JavaScript

var canvas = document.getElementById("output");

var dc = canvas.getContext("2d");

Page 25: HTML5 Quick Start

Drawing a Rectangle// HTML

<canvas id="output" width="400" height="200"></canvas>

// JavaScript

var canvas = document.getElementById("output");

var dc = canvas.getContext("2d");

dc.strokeRect(100, 50, 200, 100);

Page 26: HTML5 Quick Start

Changing the Stroke Color// HTML

<canvas id="output" width="400" height="200"></canvas>

// JavaScript

var canvas = document.getElementById("output");

var dc = canvas.getContext("2d");

dc.strokeStyle = "red";

dc.strokeRect(100, 50, 200, 100);

Page 27: HTML5 Quick Start

Changing the Stroke Width// HTML

<canvas id="output" width="400" height="200"></canvas>

// JavaScript

var canvas = document.getElementById("output");

var dc = canvas.getContext("2d");

dc.strokeStyle = "red";

dc.lineWidth = 8;

dc.strokeRect(100, 50, 200, 100);

Page 28: HTML5 Quick Start

Drawing a Filled Rectangle// HTML

<canvas id="output" width="400" height="200"></canvas>

// JavaScript

var canvas = document.getElementById("output");

var dc = canvas.getContext("2d");

dc.fillRect(100, 50, 200, 100);

Page 29: HTML5 Quick Start

Changing the Fill Color// HTML

<canvas id="output" width="400" height="200"></canvas>

// JavaScript

var canvas = document.getElementById("output");

var dc = canvas.getContext("2d");

dc.fillStyle = "red";

dc.fillRect(100, 50, 200, 100);

Page 30: HTML5 Quick Start

Filling with Linear Gradientsvar gradient = dc.createLinearGradient(100, 50, 300, 50);

gradient.addColorStop(0, "red");

gradient.addColorStop(1, "yellow");

dc.fillStyle = gradient;

dc.fillRect(100, 50, 200, 100);

Page 31: HTML5 Quick Start

Filling with Patternsvar img = new Image();

img.src = "Wood.jpg"

img.onload = function () {

dc.fillStyle = dc.createPattern(img, "repeat"); // img == Image, Canvas, or Video

dc.fillRect(100, 50, 200, 100);

}

Page 32: HTML5 Quick Start

DemoDrawing with Paths

Page 33: HTML5 Quick Start

Pixel ManipulationCanvasRenderingContext2d provides methods for creating and manipulating imagescreateImageData – Creates empty ImageData objectgetImageData – Returns populated ImageData objectSECURITY_ERR on cross-domain imagesputImageData – Renders ImageData object

ImageData objects encapsulate image datadata property provides access to pixelsOne-dimensional array, row-first orderwidth and height properties return dimensions

Page 34: HTML5 Quick Start

Generating an Imagevar bitmap = dc.createImageData(100, 100);

for (x = 0; x < bitmap.width; x++)

for (y = 0; y < bitmap.height; y++)

drawRandomColor(bitmap, x, y);

dc.putImageData(bitmap, 0, 0);

function drawRandomColor(bitmap, x, y) {

var index = (x + y * bitmap.width) << 2;

bitmap.data[index + 0] = Math.random() * 256; // Red

bitmap.data[index + 1] = Math.random() * 256; // Green

bitmap.data[index + 2] = Math.random() * 256; // Blue

bitmap.data[index + 3] = 255; // Alpha

}

Page 35: HTML5 Quick Start

Modifying an Imagevar image = new Image();

image.src = "flowers.jpg";

image.onload = function () {

dc.drawImage(image, 0, 0, canvas.width, canvas.height);

bitmap = dc.getImageData(0, 0, canvas.width, canvas.height);

for (x = 0; x < bitmap.width; x++)

for (y = 0; y < bitmap.height; y++)

toGray(bitmap, x, y); // Helper function

dc.putImageData(bitmap, 0, 0);

}

Page 36: HTML5 Quick Start

DemoPixel Manipulation

Page 37: HTML5 Quick Start

Web WorkersMultithreaded programming in JavaScriptDedicated workers – Per-owner; can't be sharedShared workers – Can be shared by multiple owners

Workers run in sandboxed environmentNo document/DOM access or window access

Current status: working draft

IE10+

Chrome4+

Firefox3.5+

Opera10.6+

Safari4+

Page 38: HTML5 Quick Start

Starting a Dedicated Workervar worker = new Worker("add.js");

// add.js (executes on background thread)

var sum = 2 + 2;

Page 39: HTML5 Quick Start

Posting Messages from a Worker// add.js

var sum = 2 + 2;

postMessage(sum); // Post sum to the main thread

Page 40: HTML5 Quick Start

Receiving Messages from a Workervar worker = new Worker("add.js");

worker.addEventListener("message", onMessage, false);

.

.

.

function onMessage(e) {

alert(e.data); // Display sum

}

Page 41: HTML5 Quick Start

Posting Messages to a Workervar worker = new Worker("add.js");

worker.addEventListener("message", onMessage, false);

worker.postMessage({ op1: 2, op2: 2 }); // Pass values to worker

.

.

.

function onMessage(e) {

alert(e.data); // Display sum

}

Page 42: HTML5 Quick Start

Receiving Messages in a Worker// add.js

addEventListener("message", onMessage, false);

.

.

.

function onMessage (e) {

var a = e.data.op1;

var b = e.data.op2;

postMessage(a + b); // Post sum to the main thread

}

Page 43: HTML5 Quick Start

Handling Errors from a Worker// Unhandled exceptions in workers fire error events

var worker = new Worker("add.js");

worker.addEventListener("error", onError, false);

.

.

.

function onError(err) {

var script = e.filename; // Script URI (fully qualified)

var linenum = e.lineno; // Line number where error occurred

var message = e.message; // Error message

alert(message + " (" + script + ", line " + linenum + ")");

}

Page 44: HTML5 Quick Start

DemoWeb Workers

Page 45: HTML5 Quick Start

Web StorageProvides client-side storage for key-value pairsLocal storage – Persists data across sessionsSession storage – Discards data when session ends

Data stored as strings and scoped per originSubject to per-origin quotas (typically 5 MB)

Current status: working draftIE8+

Chrome5+

Firefox3.5+

Opera10.5+

Safari4+

Page 46: HTML5 Quick Start

Reading and Writing Local Storage// Write a language preference to local storage

window.localStorage.setItem("Language", "en-us");

// Read a language preference from local storage

var language = window.localStorage.getItem("Language");

if (language != null)

{

window.alert(language); // Display language value

}

Page 47: HTML5 Quick Start

Reading and Writing Integers// Write count to local storage

window.localStorage.setItem("Count", 16);

// Read count from local storage

var item = window.localStorage.getItem("Count");

if (item != null)

{

var count = parseInt(item); // Convert to integer

}

Page 48: HTML5 Quick Start

Reading and Writing Integer Arrays// Write point to local storage

var x = 100;

var y = 200;

var point = [x, y]; // Stored as "100,200"

window.localStorage.setItem("Point", point);

// Read point from local storage

var point = window.localStorage.getItem("Point");

if (point != null)

{

var coords = point.split(",");

var x = parseInt(coords[0]);

var y = parseInt(coords[1]);

}

Page 49: HTML5 Quick Start

Removing Items from Local Storage// Remove a single item

window.localStorage.removeItem("Language");

// Remove all items

window.localStorage.clear();

Page 50: HTML5 Quick Start

DemoLocal Storage

Page 51: HTML5 Quick Start

File APIAPI for reading files and their contentsFile object represents individual filesFileList object represents collections of filesFileReader provides API for reading dataBlob object represents binary data

Current status: working draft

IE10+

Chrome6+

Firefox4+

Opera12+

Safari-

Page 52: HTML5 Quick Start

Loading a File// HTML

<input type="file" id="picker" />

// JavaScript

document.getElementById("picker").addEventListener("change", onFileSelected, false);

function onFileSelected(e) {

// Get a File object representing the selected file

var file = e.target.files[0];

}

Page 53: HTML5 Quick Start

Loading Multiple Files// HTML

<input type="file" id="picker" multiple />

// JavaScript

document.getElementById("picker").addEventListener("change", onFileSelected, false);

function onFileSelected(e) {

// Get a FileList object representing the selected files

var files = e.target.files;

// Enumerate the File objects in the FileList

for (i=0; i<files.length; i++) {

var file = files[i];

}

}

Page 54: HTML5 Quick Start

Getting Information About a File// Retrieve a File from a FileList

var file = e.target.files[0];

// Get the file's name, type, size, and last-modified date

var name = file.name;

var type = file.type; // e.g., "image/jpeg"

var size = file.size;

var stamp = file.lastModifiedDate;

// Determine whether the file is an image file

if (file.type.match("image.*") {

// It's an image!

}

Page 55: HTML5 Quick Start

Reading FilesFileReader contains methods for reading filesreadAsArrayBuffer - Reads the contents of the file as an ArrayBufferreadAsBinaryString - Reads the contents of the file as a binary stringreadAsDataUrl - Reads the contents of the file as a data URLreadAsText - Reads the contents of the file as a text string

Also contains event attributes such as onload, onerror, and onprogress

Page 56: HTML5 Quick Start

Reading a Text Filevar reader = new FileReader();

reader.onload = function(e) {

// Read the file's text content from e.target.result

var data = e.target.result;

}

reader.onerror = function(e) {

// If an error occurred, make the user aware

alert(e.target.error.code); // Display error code

}

reader.readAsText(file);

Page 57: HTML5 Quick Start

Reading an Image Filevar reader = new FileReader();

reader.onload = function(e) {

// Assign data URL to src property of <img> element

var img = document.getElementById("image");

image.src = e.target.result;

}

reader.onerror = function(e) {

alert(e.target.error.code); // Display error code

}

reader.readAsDataUrl(file);

Page 58: HTML5 Quick Start

DemoFileReader

Page 59: HTML5 Quick Start

XMLHttpRequest Level 2Second-generation XMLHttpRequest (AJAX)Support for cross-origin requestsSupport for file uploads and progress eventsSupport for request time-outsSupport for binary input and output and more

Current status: working draft

IE10+

Chrome7+

Firefox4+

Opera5+

Safari-

Page 60: HTML5 Quick Start

Sending a Cross-Origin Requestvar xhr = new XMLHttpRequest();

xhr.open("GET", "http://www.wintellect.com/weather/98052", true);

xhr.addEventListener("load", onLoad, false);

xhr.send();

.

.

.

function onLoad(e) {

alert(this.responseText);

}

Page 61: HTML5 Quick Start

Handling XHR2 Errorsvar xhr = new XMLHttpRequest();

xhr.open("GET", "http://www.wintellect.com/weather/98052", true);

xhr.addEventListener("load", onLoad, false);

xhr.addEventListener("error", onError, false);

xhr.send();

.

.

.

function onError(err) {

alert("Error");

}

Page 62: HTML5 Quick Start

DemoXMLHttpRequest Level 2

Page 63: HTML5 Quick Start

WebSocketsBidirectional data channels with event-based APICommunication occurs over duplex TCP socketsConnections established via secure HTTP handshakeEncrypted (wss://) and unencrypted (ws://) trafficFriendly to firewalls and (usually) proxy servers

Current status: working draftIE

10+Chrome

14+Firefox

6+Opera11+

Safari5+

Page 64: HTML5 Quick Start

Opening and Closing a WebSocket// Open a WebSocket connection

var ws = new WebSocket("ws://echo.websocket.org");

.

.

.

// Close the connection

ws.close();

Page 65: HTML5 Quick Start

Sending WebSocket Data// Send a string

ws.send("Hello, world");

// Send an ArrayBuffer

ws.send(buffer);

// Send a Blob

ws.send(blob);

Page 66: HTML5 Quick Start

Receiving WebSocket Dataws.addEventListener("message", onMessageReceived, false);

.

.

.

function onMessageReceived(e) {

var message = e.data; // Always a string

}

Page 67: HTML5 Quick Start

Handling WebSocket Errorsws.addEventListener("error", onError, false);

.

.

.

function onError(e) {

alert(e.message);

}

Page 68: HTML5 Quick Start

Download the Code

http://www.wintellect.com/downloads/html5.zip

Page 69: HTML5 Quick Start

Be what’s next: Windows 8 Metro Apps• Find everything here

http://aka.ms/mbl-win8• Save the date! March 23: Windows 8 Developer Day

and “Nacht van Windows 8 / La Nuit de Windows 8 (app-a-thon coding night)

• Start today!• Building Windows 8 blog: http://aka.ms/mbl-win8/build• Learn with Windows 8 Dev Preview: http://aka.ms/mbl-win8/devprev • Learn about Windows Store and opportunities:

http://aka.ms/mbl-win8/store

Page 70: HTML5 Quick Start

© 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.