HTML5 Quick Start

Preview:

DESCRIPTION

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

Citation preview

HTML5 Quick Start Jeff

ProsiseCofounderWintellect

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

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

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

}

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

}

DemoBrowser Support for HTML5

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+

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;

}

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;

}

}

Requesting High Accuracynavigator.geolocation.getCurrentPosition(onPositionReady,

onError, { enableHighAccuracy: true });

Specifying a Timeout Intervalnavigator.geolocation.getCurrentPosition(onPositionReady,

onError, { timeout: 10000 });

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;

}

Canceling a Watchvar watchid =

navigator.geolocation.watchCurrentPosition(onPositionReady);

.

.

.

navigator.clearWatch(watchid);

DemoGeolocation

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+

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>

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

Internet Explorer 9 Chrome 10

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)

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>

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>

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>

DemoHTML5 Video

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

Getting a Rendering Context// HTML

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

// JavaScript

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

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

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);

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);

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);

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);

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);

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);

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);

}

DemoDrawing with Paths

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

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

}

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);

}

DemoPixel Manipulation

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+

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

// add.js (executes on background thread)

var sum = 2 + 2;

Posting Messages from a Worker// add.js

var sum = 2 + 2;

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

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

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

.

.

.

function onMessage(e) {

alert(e.data); // Display sum

}

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

}

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

}

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 + ")");

}

DemoWeb Workers

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+

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

}

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

}

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]);

}

Removing Items from Local Storage// Remove a single item

window.localStorage.removeItem("Language");

// Remove all items

window.localStorage.clear();

DemoLocal Storage

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-

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];

}

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];

}

}

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!

}

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

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);

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);

DemoFileReader

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-

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);

}

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");

}

DemoXMLHttpRequest Level 2

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+

Opening and Closing a WebSocket// Open a WebSocket connection

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

.

.

.

// Close the connection

ws.close();

Sending WebSocket Data// Send a string

ws.send("Hello, world");

// Send an ArrayBuffer

ws.send(buffer);

// Send a Blob

ws.send(blob);

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

.

.

.

function onMessageReceived(e) {

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

}

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

.

.

.

function onError(e) {

alert(e.message);

}

Download the Code

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

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

© 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.

Recommended