Beruflich Dokumente
Kultur Dokumente
Development
HTML5
HISTORY
1994
1996
1997
1998
2000
2002
2005
2009
slides.html5rocks.com/#timeline-slide
23.04.2013 HTML5 | Andreas Jakl, Mopius 5
MIME Types
– Header of web server response:
• Content-Type: text/html
• Identifies resource and how to render it
HTTP/1.1 200 OK
Date: Sun, 21 Apr 2013 16:31:39 GMT
Server: Apache
Last-Modified: Wed, 03 Apr 2013 13:53:04 GMT
ETag: "3962805-3d8-4d9752c459000"
Accept-Ranges: bytes
Content-Length: 984
Connection: close
Content-Type: text/html
<html>
</head>
<body>
Hello world!
DETECTING HTML 5
– Specific mobile
• mobilehtml5.org
<meta charset="utf-8">
<!DOCTYPE html>
<meta charset=utf-8>
<title>My company</title>
<p>We strive for the best!</p>
– Alternate
<link rel="alternate"
type="application/rss+xml"
title="NfcInteractor.com » Feed"
href="http://www.nfcinteractor.com/feed/" />
dev.w3.org/html5/spec-LC/links.html#rel-icon
23.04.2013 HTML5 | Andreas Jakl, Mopius 39
HTML5 Template
– Basic HTML5 starting point, e.g.:
• HTML5 Boilerplate
html5boilerplate.com/
• HTML5 Reset
html5reset.org/
SEMANTICS
IE <= 8: style not applied, child items added as silblings to DOM. Workaround:
github.com/aFarkas/html5shiv/
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<h1>Hello</h1> <h1>Hello</h1>
<div> <article>
<h1>World</h1> <h1>World</h1>
</div> </article>
gsnedders.html5.org/outliner/
23.04.2013 HTML5 | Andreas Jakl, Mopius 53
Header Groups
– Prevent header from appearing in outline
• E.g., for subheader
<h1>mopius.com</h1> <hgroup>
<h2>Mobile Professionals</h2> <h1>mopius.com</h1>
<h2>Our offering</h2> <h2>Mobile Professionals</h2>
</hgroup>
<h2>Our offering</h2>
www.w3.org/WAI/intro/aria
msdn.microsoft.com/en-us/library/gg701982%28v=vs.85%29.aspx
23.04.2013 HTML5 | Andreas Jakl, Mopius 56
Machine-Understandable Page Contents
MORE SEMANTICS
Metadata Not present on page. Influences title, style, script, meta, ...
presentation / behavior / relationships.
Flow Most elements in body div, header, a, p, ...
Sectioning Scope of headings and footers article, aside, nav, section
Heading Header of a section h1, ..., h6, hgroup
Phrasing Roughly like inline content b, small, span, time, ...
Embedded Imports resource img, audio, embed, canvas, video, ...
Interactive For user interaction input, textarea, video (with controls), ...
dev.w3.org/html5/spec-LC/content-models.html
23.04.2013 HTML5 | Andreas Jakl, Mopius 59
Date / Time
– Machine-readable date Published <time title="Wed Apr 10 15:40:07 2013 UTC"
and/or time datetime="2013-04-10T15:40:07+00:00">3 hours</time> ago.
xahlee.info/js/html5_figure_figurecaption.html
23.04.2013 HTML5 | Andreas Jakl, Mopius 61
Mark
– “Highlight part of the document
due to its likely relevance to the
user’s current activity”
www.w3.org/html/wg/drafts/html/master/text-level-semantics.html#the-mark-element
23.04.2013 HTML5 | Andreas Jakl, Mopius 62
No value & max
Progress → indeterminate
– Progress
• Completion progress of a task
• Indeterminate (e.g., connection to web server) or
known range (0 .. max, download progress)
<section>
<h2>Task Progress</h2>
<p>Progress: <progress id="p" max="100"><span>0</span>%</progress></p>
<script>
var progressBar = document.getElementById('p');
function updateProgress(newValue) {
progressBar.value = newValue;
progressBar.getElementsByTagName('span')[0].textContent = newValue;
}
updateProgress(70);
</script>
</section>
www.w3.org/html/wg/drafts/html/master/obsolete.html#frames
23.04.2013 HTML5 | Andreas Jakl, Mopius 65
Changes to Existing Features
– Block elements inside links
• Now allowed – e.g., multi-paragraph link
<figure>
<blockquote>
<p>The truth may be puzzling. It may take some work to grapple with. It may be counterintuitive.
It may contradict deeply held prejudices. It may not be consonant with what we desperately want
to be true. But our preferences do not determine what's true. We have a method, and that method
helps us to reach not absolute truth, only asymptotic approaches to the truth — never there, just
closer and closer, always finding vast new oceans of undiscovered possibilities. Cleverly
designed experiments are the key.</p>
</blockquote>
<figcaption>Carl Sagan, in "<cite>Wonder and Skepticism</cite>", from
the <cite>Skeptical Enquirer</cite> Volume 19, Issue 1 (January-February
1995)</figcaption>
</figure>
WEB FORMS
www.html5rocks.com/en/tutorials/forms/html5forms/
23.04.2013 HTML5 | Andreas Jakl, Mopius 72
New Input Types
– Advantages 13 new types
• No specific UI mandated by spec email url
date time
• Devices can use optimized UI
datetime datetime-local
– Special virtual keyboard for emails on
phones month week
– Calendar-style date picker number range
field color
<form novalidate>
demo.agektmr.com/datalist/
23.04.2013 HTML5 | Andreas Jakl, Mopius 75
Virtual Keyboards
url email
<form>
<input name="username" placeholder="Username">
<input type="submit" value="Login">
</form>
<form>
<input name="username" autofocus>
<script>
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("username").focus();
}
</script>
<input type="submit" value="Login">
</form>
Default style
in Chrome
– Required field not filled?
• Form fails to submit
• Focus moves to first invalid field
<style>
• Automatic error message input:required {
var i = document.createElement("input");
i.setAttribute("type", "color");
return i.type !== "text";
var i = document.createElement('input');
return 'placeholder' in i;
var i = document.createElement('input');
return 'autofocus' in i;
CANVAS
<script>
function draw_rect() {
var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
context.fillRect(25, 50, 100, 30);
}
</script>
<canvas id="c" width="300" height="225" style="border:1px
dotted;float:left" onclick="draw_rect();return false"></canvas>
Context ID
2d
webgl
Vendor-specific extension
1 1
2 2
3 3
– Quadratic curves
context.quadraticCurveTo(cp1x, cp1y, x, y);
– Bezier curves
context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
developer.mozilla.org/samples/canvas-tutorial/6_1_canvas_composite.html
23.04.2013 HTML5 | Andreas Jakl, Mopius 103
Clipping Paths
– Similar to source-in compositing
• But doesn’t actually draw 2nd object
ctx.beginPath();
// Define clipping path
ctx.arc(0,0,60,0,Math.PI*2,true);
// Apply
ctx.clip();
// Draw the clipped contents ...
developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial/Compositing
23.04.2013 HTML5 | Andreas Jakl, Mopius 104
Clearing the Canvas
– Clear function
• Preferred, faster!
• Doesn’t reset transformation matrix
context.clearRect(0, 0, canvas.width, canvas.height);
– Drawing
• Load the image from <img> or entirely in JavaScript (and ensure it’s loaded)
var curvesImg = new Image();
curvesImg.src = "curves.png";
curvesImg.onload = function() {
context.drawImage(curvesImg, 0, 0);
}
www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dfnReturnLink-16
23.04.2013 HTML5 | Andreas Jakl, Mopius 108
Animations
– Drawing
• When script execution finishes
– Scheduling
• setInterval() – calls function repeatedly, fixed delay
• setTimeout() – calls function after specified delay
– Examples
• developer.mozilla.org/en-US/docs/HTML/Canvas/Tutorial/Basic_animations
www.w3.org/TR/animation-timing/#requestAnimationFrame
23.04.2013 HTML5 | Andreas Jakl, Mopius 110
<script>
var requestId = 0;
function animate(time) {
var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillRect(Math.abs((time - animationStartTime) % 2000 / 4), 0, 50, 50);
context.fillText(animationStartTime, 10, 70);
context.fillText(time, 10, 90);
requestId = window.requestAnimationFrame(animate);
}
function start() {
animationStartTime = Date.now();
requestId = window.requestAnimationFrame(animate);
}
function stop() {
if (requestId)
window.cancelAnimationFrame(requestId);
requestId = 0;
}
</script>
<button onclick="start()">Click me to start!</button><br>
<button onclick="stop()">Click me to stop!</button><br>
mozilla.org/en-US/docs/HTML/Canvas/Tutorial/Optimizing_canvas
23.04.2013 HTML5 | Andreas Jakl, Mopius 112
Pre-Rendering
no pre-rendering pre-rendering
// canvas, context are defined var m_canvas =
function render() { document.createElement('canvas');
drawMario(context); m_canvas.width = 64;
requestAnimationFrame(render); m_canvas.height = 64;
} var m_context = m_canvas.getContext(‘2d’);
drawMario(m_context);
function render() {
context.drawImage(m_canvas, 0, 0);
requestAnimationFrame(render);
}
www.html5rocks.com/en/tutorials/canvas/performance/
23.04.2013 HTML5 | Andreas Jakl, Mopius 113
Batch Canvas Calls Together
Single lines Poly lines
for (var i = 0; i < points.length - 1; i++) context.beginPath();
{ for (var i = 0; i < points.length - 1; i++)
var p1 = points[i]; {
var p2 = points[i+1]; var p1 = points[i];
context.beginPath(); var p2 = points[i+1];
context.moveTo(p1.x, p1.y); context.moveTo(p1.x, p1.y);
context.lineTo(p2.x, p2.y); context.lineTo(p2.x, p2.y);
context.stroke(); }
} context.stroke();
www.html5rocks.com/en/tutorials/canvas/performance/
23.04.2013 HTML5 | Andreas Jakl, Mopius 114
Batch Canvas Calls Together
Single lines Poly lines
for (var i = 0; i < points.length - 1; i++) context.beginPath();
{ for (var i = 0; i < points.length - 1; i++)
var p1 = points[i]; {
var p2 = points[i+1]; var p1 = points[i];
context.beginPath(); var p2 = points[i+1];
context.moveTo(p1.x, p1.y); context.moveTo(p1.x, p1.y);
context.lineTo(p2.x, p2.y); context.lineTo(p2.x, p2.y);
context.stroke(); }
} context.stroke();
www.html5rocks.com/en/tutorials/canvas/performance/
23.04.2013 HTML5 | Andreas Jakl, Mopius 115
Avoid Unnecessary State Changes
– State changes expensive (colors, style, etc.)
• → render by style instead of by placement
Striped pattern, by placement By color
for (var i = 0; i < STRIPES; i++) { context.fillStyle = COLOR1;
context.fillStyle = (i % 2 ? COLOR1 : COLOR2); for (var i = 0; i < STRIPES/2; i++) {
context.fillRect(i * GAP, 0, GAP, 480); context.fillRect((i*2) * GAP, 0, GAP, 480);
} }
context.fillStyle = COLOR2;
for (var i = 0; i < STRIPES/2; i++) {
context.fillRect((i*2+1) * GAP, 0, GAP, 480);
}
www.html5rocks.com/en/tutorials/canvas/performance/
23.04.2013 HTML5 | Andreas Jakl, Mopius 116
Layered Canvases
– Static background, dynamic contents on top?
• Use two canvases on top of each other
• HW acceleration composits alphas together
<canvas id="bg" width="640" height="480" style="position: absolute; z-index: 0">
</canvas>
<canvas id="fg" width="640" height="480" style="position: absolute; z-index: 1">
</canvas>
www.w3.org/TR/html5/embedded-content-0.html#the-canvas-element
23.04.2013 HTML5 | Andreas Jakl, Mopius 119
Detection: Canvas
– Create & call method of canvas element
• Only has common properties? → not supported
return !!(is(document.createElement('canvas')
.getContext('2d').fillText, 'function'));
TOUCH EVENTS
dvcs.w3.org/hg/webevents/raw-file/tip/touchevents.html
23.04.2013 HTML5 | Andreas Jakl, Mopius 125
Touch Example
1 2
var touches = []; // In game loop
var i, len = touches.length;
canvas.addEventListener('touchmove', for (i=0; i<len; i++) {
function(event) { var touch = touches[i];
touches = event.touches; var px = touch.pageX;
}); var py = touch.pageY;
canvas.addEventListener('touchstart', ctx.beginPath();
function(event) { ctx.arc(px, py, 20, 0, 2*Math.PI, true);
// Prevent mouse events or scrolling // ...
event.preventDefault();
});
www.html5rocks.com/en/mobile/touch/
23.04.2013 HTML5 | Andreas Jakl, Mopius 126
Exercise: Canvas Painter Touch
– Extend Canvas Painter example for touch events
• touchstart
• touchmove
• touchend
– Touch simulation
• developers.google.com/chrome-developer-
tools/docs/mobile-emulation#emulate-touch-events
Chrome
Internet Explorer
www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#the-source-element
23.04.2013 HTML5 | Andreas Jakl, Mopius 138
Different Devics
– Use file size-optimized version for devices
• Use CSS3 media query:
www.w3.org/TR/css3-mediaqueries/
<video width="640" height="360" controls>
<source src='NearSpeak-hq.webm' type='...' media="(min-device-width: 800px)" />
<source src='NearSpeak.webm' type='...' />
</video>
developer.mozilla.org/en-US/docs/Properly_Configuring_Server_MIME_Types
23.04.2013 HTML5 | Andreas Jakl, Mopius 140
Media Elements API
– Control playback with JavaScript
• Allows custom style for video control
• Query video properties and load / playback state
www.w3.org/2010/05/video/mediaevents.html
23.04.2013 HTML5 | Andreas Jakl, Mopius 141
HTML5 Audio
– Similar to video
– Can also be hidden
• Control via JavaScript only
var audio = new Audio('music.mp3');
audio.play();
return !!document.createElement('video').canPlayType;
document.createElement('video').canPlayType('video/ogg; codecs="theora"')
• Browser-specific parseInt(localStorage.pageLoadCount) + 1;
document.getElementById('count').textContent =
localStorage.pageLoadCount;
– Can’t access IE data from </script>
FireFox
• Recommended: 5 MB limit
// Store data
sessionStorage.setItem('html5knowledge', JSON.stringify(html5knowledge) );
✘
✔
// Read stored data
var html5knowledge2 = JSON.parse(sessionStorage.getItem('html5knowledge'));
document.write(html5knowledge2.topic + ": " + html5knowledge2.percent);
– Open database
var bookData = [
• Each DB has a version (and only 1) { name: "The Name of the Wind", isbn: "0575081406" },
• Success and error callbacks ];
{ name: "Dune", isbn: "0441172717" }
var db;
var request = indexedDB.open("BookDB", 1); // Version 1
request.onsuccess = function (evt) {
db = request.result;
};
request.onerror = function (evt) {
console.log("Database error: " + evt.target.errorCode);
};
www.codeproject.com/Articles/325135/Getting-Started-with-IndexedDB
www.ibm.com/developerworks/web/library/wa-indexeddb/index.html
23.04.2013 HTML5 | Andreas Jakl, Mopius 160
Object Stores, Keys & Values
– 1+ objectStores in DB (like tables in relational DBs)
• Can only be created / modifying when changing the objectStore version!
• Each object store: list of records (key + value)
– Key
• Key is unique
• Valid types: Array (its numeric properties), DOMString, Date, float
1. Optional key generators create main index
2. Optional key path defines how to extract key from value (in-line keys)
3. Alternatives: pass own key / use autoIncrement
– Indexes
• 0+ indexes used for data retrieval
• Index = list of records (their key paths)
• Optionally unique
– Add data
var request = objectStore.add({ name: addName, isbn: addIsbn});
– Handle success
request.onsuccess = function (evt) { // do something after the add succeeded };
www.whatwg.org/specs/web-apps/current-work/multipage/offline.html
23.04.2013 HTML5 | Andreas Jakl, Mopius 167
Application Cache vs Browser Cache
– Automatic browser cache
• Speeding up website loading, avoids reloading files
• But:
– All files cached, open website without internet connection
→ Error
– Offline Web Apps
• We define which pages to cache or fetch from network
• Events: window.online
window.offline
GEOLOCATION
www.w3.org/TR/geolocation-API/
23.04.2013 HTML5 | Andreas Jakl, Mopius 178
Security
– Visitors must opt-in
• Nothing passed to website until
user accepted
• Website can’t by-pass infobar
• Privacy policy requirements for
location recipients
if (Modernizr.geolocation) {
// One-shot position request.
navigator.geolocation.getCurrentPosition(showMap);
} else {
// no native support; maybe try a fallback?
alert("No geolocation support");
}
</script>
– PositionError – code:
• PERMISSION_DENIED: 1
– E.g., user didn’t accept location request
• POSITION_UNAVAILALBE: 2
– E.g., internal error getting the location
• TIMEOUT: 3
– Time specified in request has elapsed
– PositionError – message:
• Describes details – only for developer & debugging, should not be used in UI
MOTION SENSORS
dev.w3.org/geo/api/spec-source-orientation.html
23.04.2013 HTML5 | Andreas Jakl, Mopius 188
Physical Orientation
– Rotation determined based on Earth coordinate system (East, North, Up)
Up
North
East
Up
North
East
PERFORMANCE
dev.w3.org/html5/workers/
23.04.2013 HTML5 | Andreas Jakl, Mopius 195
Dedicated vs Shared
– Dedicated Worker
• Linked to the script that created it
– Shared Worker
• Accessed by any script from the same origin
• Cross-worker communication
slides.html5rocks.com/#web-workers
23.04.2013 HTML5 | Andreas Jakl, Mopius 196
Access & Messages
– Limitations of Workers
• No access to DOM, window, document or parent objects
• No access to global variables / functions from main page
• Chrome: locally run (file://) workers fail silently
– Run Chrome with: --allow-file-access-from-files
– Communication
• Messages between worker and main page
• Data: string or JSON, copied when passing
– Start
worker.postMessage();
– Communicate
doWork.js
main.html
worker.postMessage('Hello World');
www.html5rocks.com/en/tutorials/workers/basics/
23.04.2013 HTML5 | Andreas Jakl, Mopius 198
Prime Numbers Example
webworker.html
worker.js
<!DOCTYPE HTML> var n = 1;
<html> search: while (true) {
<head> n += 1;
<title>Worker example</title> for (var i = 2; i <= Math.sqrt(n); i += 1)
</head> if (n % i == 0)
<body> continue search;
<p>The highest prime number discovered so // found a prime!
far is: <output id="result"></output></p> postMessage(n);
<script> }
var worker = new Worker('worker.js');
worker.onmessage = function (event) {
document.getElementById('result').
textContent = event.data;
};
</script>
</body>
</html>
dev.w3.org/html5/workers/#a-background-number-crunching-worker
Maps example: slides.html5rocks.com/#web-workers
23.04.2013 HTML5 | Andreas Jakl, Mopius 199
Worker Features
– Transferrable objects
• Move objects from main page to script context
– Not accessible from main page anymore
• Improves performance for large objects
– External scripts
• Import external scripts: importScripts('script1.js');
– Spawn subworkers
– Inline workers
• Execute worker without its individual .js file
THANK YOU.