HTML 5

HTML DOM

  • getElementsByClassName()
  • getSelection()
  • activeElement
  • hasElement
  • designMode
  • execCommand()

Tags

Added

  • wbr: Allows the browser to wrap the text, without adding whitespace
  • mark: Text that should be highlighted
  • header: Top of a document or section
  • footer: Bottom of a document or section
  • section: A basic structural part of the document
  • nav: Container for a set of navigation elements
  • hgroup: Container for a set of heading tags (e.g., table of contents)
  • details: Info about the document or website itself
  • summary: The header for a details tag
  • figure: Standalone content not essential to the flow of the page
  • aside: Related content
  • article: Content from an external source
  • embed: Embedded content, like a plug-in
  • canvas
  • audio
  • video
  • progress: Progress bar
  • meter: Gauge showing a measurement
  • time: Time or date or both
  • output: Displays the result of a calculation (e.g., a value calculated by a script)
  • datalist: Container for a list of option tags, associated with an input tag (input list="abc"... datalist id="abc")
  • command: Button, radio button, or checkbox
  • keygen: Key-pair generator field

Not added

  • bb (browser button): Use the button tag instead
  • datagrid: Use the datalist tag instead
  • dialog: Use a p tag instead (in combination with b and i tags, etc.)

Dropped

  • basefont
  • big
  • center
  • font
  • s
  • strike
  • tt
  • u
  • frame
  • frameset
  • noframes
  • acronym (use abbr)
  • applet (use object)
  • isindex (use form controls)
  • dir (use ul)

Attributes

Global attributes available for every tag

  • id
  • tabindex
  • hidden

Added

  • async (script)
  • charset (meta)
  • draggable
  • contenteditable
  • ping (a, area)

Dropped

  • language (script)
  • target (link)
  • name (img, a) (use id)
  • shape and coords (a)
  • version (html)
  • scheme (meta)
  • accesskey (a, area, button, input, label, legend and textarea)
  • rev and charset (link, a)
  • longdesc (img, iframe)
  • nohref (area)
  • profile (head)
  • archive, classid, codebase, codetype, declare and standby (object)
  • valuetype and type (param)
  • summary (table)
  • axis and abbr (td, th)
  • scope (td)
  • align (caption, iframe, img, input, object, legend, table, hr, div, h1, h2, h3, h4, h5, h6, p, col, colgroup, tbody, td, tfoot, th, thead, tr)
  • alink, link, text and vlink (body)
  • background (body)
  • bgcolor (table, tr, td, th and body)
  • border (table, img, object)
  • cellpadding and cellspacing (table)
  • char and charoff (col, colgroup, tbody, td, tfoot, th, thead, tr)
  • clear (br)
  • compact (dl, menu, ol, ul)
  • frame (table)
  • frameborder (iframe)
  • height (td, th)
  • hspace and vspace (img, object)
  • marginheight and marginwidth (iframe)
  • noshade (hr)
  • nowrap (td, th)
  • rules (table)
  • scrolling (iframe)
  • size (hr)
  • type (li, ol, ul)
  • valign (col, colgroup, tbody, td, tfoot, th, thead, tr)
  • width (hr, table, td, th, col, colgroup, pre)

Forms

  • New form controls: dates and times, email, url, search, color
  • The form attribute (input, output, select, textarea, button, fieldset) allows controls to be associated with a form, without having to nest them within the form
  • Empty form tags can be nested within the head tag
  • The action, enctype, method, novalidate, and target attributes on input and button elements have been renamed to formaction, formenctype, formmethod, formnovalidate, and formtarget, respectively.

Web Forms 2.0

  • Basic type and validity checking
  • Allowable behavior for some form elements
  • Additional input types
  • Extensions to submit buttons
  • Error handling for unexpected elements and values
  • Event model for form elements
  • Updated form submission specification

Additional input types

  • datetime, datetime-local, date, month, week, time, number, range, email, url, search, color
  • For most of these input types, min, max and step attributes can be used.
datetime
  • UTC time zone
  • YYYY-MM-DDTHH:MM[:SS[.SS]]Z
  • 1995-01-02T12:34:56.78Z
  • step attribute is in seconds (default: 60)
datetime-local
  • No time zone info
  • YYYY-MM-DDTHH:MM[:SS[.SS]]
  • 1995-01-02T12:34:56.78
  • step attribute is in seconds (default: 60)
date
  • YYYY-MM-DD
  • 1995-01-02
  • step attribute is in days (default: 1)
month
  • YYYY-MM
  • 1995-01
  • step attribute is in months (default: 1)
week
  • YYYY-WNN
  • 1995-W32
  • step attribute is in weeks (default: 1)
time
  • No time zone info
  • HH:MM[:SS[.SS]]
  • 12:34:56.78
  • step attribute is in seconds (default: 60)
number
  • The submission format is [-NN].NN[e[-]NN]
  • step attribute defaults to 1
range
  • step attribute defaults to 1
  • min defaults to 0
  • max defaults to 100

Canvas

  • Created by Apple
  • Standardized by WHATWG (Apple, Mozilla, Opera)
  • Not yet standardized by W3C
  • Grid coordinates are similar to screen coordinates (the top-left corner is 0, 0)
<canvas id="myCanvas" width="150" height="150"></canvas>
...
var canvas = document.getElementById('myCanvas');
if (canvas.getContext) {
    var ctx = canvas.getContext('2d');
    ...
}
  • Setting the width or height of a canvas DOM element will erase its contents and reset all the properties  of its drawing context to their default values, even if the width or height do not change.
  • After the drawing is completed, the updated canvas is displayed (once the UI is free again)
  • The use of dual frame buffers makes no noticeable difference
  • Drawing in an invisible or hidden canvas, or in an invisible container, which is made visible afterwards, has no noticeable effect on the speed of the rendering

Limitations

Contexts
  • The only context defined in the early specification is '2d'
  • Later specifications may also have a '3d' context
Web workers
  • The actual drawing can only be done by the main thread, which holds up the browser until it's done
Gradients
  • Gradients using more than 2 color points are not supported (i.e. a rectangle or triangle with a different color point at each corner)
  • Only simple gradients are possible
  • Transparency and composites blend color in a different way than gradients and as such are not useful for faking complex gradients

Hacks

3D textures
  • 3D texture mapping can be approximated in a 2D canvas by breaking up the surface into small triangles and drawing and clipping each triangle separately
  • The end result is as if all of the pixels for each individual triangle are at the same distance

Drawing crisp lines

ctx.moveTo(75, 10);   ctx.lineTo(75, 90);     // Blurred; drawing in-between pixel rows
ctx.moveTo(75.5, 10); ctx.lineTo(75.5, 90);   // Crisp; drawing on a pixel row

Basic functions

beginPath()
...
closePath()

fill()         // For a filled shape
stroke()       // For an outlined shape

save()         // Push the canvas state to the stack
...
restore()      // Pop the canvas state
Values saved in the canvas state
  • Properties: strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation
  • Transformations: translate, rotate, scale
  • Clipping path

Rectangles

fillRect(x, y, width, height)     // Filled rectangle
strokeRect(x, y, width, height)   // Rectangular outline
clearRect(x, y, width, height)    // Clear the area and make it transparent

rect(x, y, width, height)         // Adds a rectangular path to the path list

Polygons

moveTo(x, y)
lineTo(x, y)   // Adds a path to the path list

Curves

arc(x, y, radius, startAngle, endAngle, anticlockwise)   // Adds a curved path to the path list

quadraticCurveTo(cp1x, cp1y, x, y)
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

Images

drawImage(image, x, y)
drawImage(image, x, y, width, height)   // Scaled image
drawImage(image, srcx, srcy, srcWidth, srcHeight, destx, desty, destWidth, destHeight)    // Clipped, scaled image
Using an img element
<img id="myImage" .../>
...
var img = document.getElementById('myImage');
ctx.drawImage(img, 0, 0);                       // Note: Make sure the image has loaded
Creating an image from scratch
var img = new Image();
img.src = 'myImage.png';
img.onload = function() { ctx.drawImage(img, 0, 0); }

Color

fillStyle = color
strokeStyle = color
Sample values
"orange"
"#FFA500"
"rgb(255, 165, 128)"
"rgba(255, 165, 128, 1)"
"hsl(50%, 50%, 50%)"

Transparency

globalAlpha = transparencyValue
Values
0.0  : fully transparent
1.0  : fully opaque (default)

Line styles

lineWidth = value
lineCap = type          // 'butt', 'round', 'square'
lineJoin = type         // 'round' (rounded edges), 'bevel' (flattened edges), 'miter' (sharp edges)
miterLimit = value      // How far the ends of joined lines can be extended for a sharp edge

Pixel manipulation

context.createImageData(width, height)      // Returns: imageData
context.getImageData(x, y, width, height)   // Returns: imageData
context.putImageData(imageData, x, y)       // FF 3.5 doesn't support non-zero x and y values
context.putImageData(imageData, x, y, imageX, imageY, imageWidth, imageHeight)  // Supp: Saf4, Chr4; Not: FF3.5

Accessing image data with a web worker

imageData.width
imageData.height
imageData.data[]
imageData.data.length
// Receive image data
worker.onmessage = function(e) {
    var imageData  = e.data;
    var frame = context.createImageData(canvas.width, canvas.height);
    frame.data = imageData;             // or: Array.prototype.concat.call(frame.data, imageData)
    context.putImageData(frame, 0, 0);
};
// Send image data
var ctxImgData = context.getImageData(0, 0, canvas.width, canvas.height);
worker.postMessage(ctxImgData.data);
...
// worker1.js
onmessage = function(e) {
    var imageData = e.data;
    for (var y = 0; y < imageData.height; y++) {      // For each row
        for (var x = 0; x < imageData.width; x++) {   // For each column in the row
            for (var i = 0; i < 4; i++) {             // For each rgba value (0..255, 0: transp, 255: opaque)
                imageData.data[(((y * imageData.width) + x) * 4) + i] = 255;   // Set the pixel to white
            }
        }
    }
    postMessage(imageData);
}

Gradients

  • Linear gradients can have 2 or more color points (on the same line)
  • Radial gradients can have 2 or more color points
createLinearGradient(x1, y1, x2, y2)
createRadialGradient(x1, y1, r1, x2, y2, r2)

addColorStop(position, color)    // Position: 0.0 - 1.0
var lingrad = ctx.createLinearGradient(0, 0, 0, 150);
lingrad.addColorStop(0, '#00ABEB');
lingrad.addColorStop(1, '#fff');

ctx.fillStyle = lingrad;
ctx.fillRect(10, 10, 130, 130);

Patterns

createPattern(image, type)   // Type: 'repeat', 'repeat-x', 'repeat-y', 'no-repeat'
var ptrn = ctx.createPattern(img, 'repeat');
ctx.fillStyle = ptrn;
ctx.fillRect(0, 0, 150, 150);

Shadows

shadowOffsetX = float    // Default: 0
shadowOffsetY = float    // Default: 0
shadowBlur = float       // Default: 0
shadowColor = color      // Default: fully-transparent black

Font

font = type
ctx.font = "20px Times New Roman";
ctx.fillStyle = "Black";
ctx.fillText("Hello", 5, 30);

Transformations

translate(xby, yby)   // Move the canvas origin to a different point on the grid
rotate(angle)         // Rotate the canvas around the current origin
scale(xby, yby)       // Scale the units in the canvas grid (the scaling is centered on the current origin)
transform(m11, m12, m21, m22, dx, dy)      // Multiply the current transformation matrix with the specified values
setTransform(m11, m12, m21, m22, dx, dy)   // Set the transformation matrix to the specified values

    m11   m21    dx
    m12   m22    dy
      0     0     1

Compositing

globalCompositeOperation = type
Compositing values
source-over        The new shape is drawn on top of the canvas content (default)
destination-over   The new shape is drawn below the canvas content

source-in          The new shape is clipped to the canvas content; everthing else is made transparent
destination-in     The canvas content is kept where it overlaps with the new shape; everything else is made transparent

source-out         The new shape is only drawn outside of the canvas content
destination-out    The canvas content is kept where it doesn't overlap the new shape

source-atop        The new shape is clipped to the canvas content
destination-atop   The canvas content is clipped to the new shape

lighter            Adds the color values for overlapping areas
darker             Subtracts the color values for overlapping areas

xor                Shapes are transparent where both overlap
copy               Draws the new shape and removes everything else

Clipping paths

clip()    // Use the current path list as a clipping shape for the canvas

Animation

setInterval(myDrawFunction, 500);   // Update the canvas every 500 milliseconds
setTimeout(myDrawFunction, 500);    // Update the canvas one time after 500 milliseconds
var img = new Image();
function init(){
    img.src = 'images/icon.png';
    setInterval(draw, 100);
}
function draw() {
    var ctx = document.getElementById('canvas').getContext('2d');
    ctx.drawImage(img, 50, 50, 100, 100);
    ...
}

Web workers

  • Background scripts
  • Similar to threads
  • Spawn background workers that run scripts in parallel to the main page
  • Use message-passing to coordinate the workers with the main thread
  • Runs in a sandbox (no access to the DOM or the global space of the main thread)
  • Communication with the main thread is limited to serialized messages
  • Useful for performing calculations in the background
  • Have to delegate UI actions to the main thread (using postMessage, onmessage)
  • Runs independently of the main thread (which handles UI events) and other workers
  • Don't have to yield to keep the page responsive
  • Expensive to create and run
  • Most efficient when long-lived and used in small numbers

Creating a worker

var worker = new Worker('worker1.js');   // Dedicated worker

Subworkers

  • Workers can create sub-workers
  • Must be hosted within the same origin as the parent page
  • URIs for subworkers are relative to the parent worker's location

Stopping a worker

  • Immediately terminate a worker: worker.terminate()
  • Have a worker terminate itself: close()

Worker scope

  • Workers run in their own global scope, which can be explicity referenced using the "self" object.

Properties and methods available

  • XMLHttpRequest constructor: responseXML and channel attributes are always null
  • "self" object: the global object for the worker
  • ECMAScript constructors
  • navigator object: appName, appVersion, userAgent, platform
  • location object: similar to window.location but all properties are read-only
  • setTimeout(), setInterval(), clearTimeout(), clearInterval()
  • importScripts(): for loading external JavaScript files into the worker’s scope

Coordinating workers

  • String messages can be passed between the main thread and a worker (in either direction)
  • Convert JSON-compatible objects to strings and back again (no methods or circular references)

Communicating with a worker

  • Send a message to the worker:
worker.postMessage(...);
  • Receive a message from the main thread:
onmessage = function (e) { var data = e.data; ... };

Communicating with the main thread

  • Send a message to the main thread:
postMessage(...);
  • Receive a message from the worker:
worker.onmessage = function (e) { var data = e.data; ... };
  • Avoid flooding the main thread with messages from the web workers, or else the browser won't be responsive to UI events

Sample 2-way message passing

var worker = new Worker('worker1.js');
worker.onmessage = function (event) { alert(event.data); };
worker.postMessage("123");
...
// worker1.js
onmessage = function(event){
    postMessage(event.data + ' received');
};
var worker = new Worker('worker1.js');
worker.postMessage( data.sha + " " + data.words.join(",") + " " + data.best );
...
// worker1.js
onmessage = function(e){
    var parts = e.data.split(" ");
    data = { sha: parts[0], words: parts[1].split(","), best: parts[2] };
    ...
};

Browser support

  • To a varying extent: FF 3.5, Safari 4, Chrome 4, Opera 10
  • Very limited support: IE 8
  • Limited support: IE 9
  • Web Forms 2.0: Op 11, Op Mob (Partial support: IE10, Saf 4, Chr 4, Op 10)
  • Canvas: IE9, FF 3.5, Saf 4, Chr 4, Opera 10, Chrome Frame (IE), Saf Mob, Andr
  • Canvas text: IE9, FF 3.5, Saf 4, Chr 4, Op, Saf Mob, Andr
  • Audio: IE9, FF 3.5, Saf 4, Chr 4, Op, Saf Mob 4, Andr 2.3
  • Video: IE9, FF 3.5, Saf 4, Chr 4, Op, Saf Mob 4, Andr 2.3
  • Geolocation: IE9, FF 3.5, Saf 5, Chr, Op, Saf Mob, Andr
  • Web workers: IE10, FF 3.5, Saf 4, Chr 4, Op, Op Mob 11 (x: IE9, Saf Mob, Andr)

Alternatives for IE

  • Google Chrome Frame: plug-in; embeds Chrome within IE; includes V8 JavaScript engine; supports canvas, ...; does not support web workers, ...
  • Declaring that a page should be rendered using Chrome Frame when available:
<meta http-equiv="X-UA-Compatible" content="chrome=1" />
  • There are independent efforts to support the canvas tag in IE using VML and JavaScript (without requiring a plug-in)
  • ExplorerCanvas: Created by Google (not currently supported: patterns, radial gradients, clipping paths, painting mode, ...)
<!--[if IE]><script src="excanvas.js"></script><![endif]-->
  • XForms processor: plug-in; provides support for the canvas element; created by Novell

Misc

  • DOCTYPE declaration (not needed for XHTML)
<!DOCTYPE html>
  • The XHTML variant of this is XHTML 5
  • As of 2009, the standard has not been officially defined.
  • SVG and MathML elements can be used

Existing Usage

  • Google Wave requires a browser that supports HTML 5.
  • Google has been especially interested in canvas, video, web workers, geolocation, and offline storage.

Offline storage

  • Local database and application cache
  • Based on SQLite
  • This may have been changed to a standalone specification outside of HTML 5

 

Resources

Sources

  • http://en.wikipedia.org/wiki/HTML_5
  • http://www.findmebyip.com/litmus/ - HTML5 and CSS3 Support
  • http://en.wikipedia.org/wiki/Comparison_of_layout_engines_(HTML5) - Browser support
  • http://www.deepbluesky.com/blog/-/browser-support-for-css3-and-html5_72/
  • http://www.quirksmode.org/compatibility.html - Browser Compatibility
  • http://www.smashingmagazine.com/2009/08/04/designing-a-html-5-layout-from-scratch/ - Progressive Enhancement vs Graceful Degradation
  • http://whatwg.org/ww - Web Workers Specification
  • https://developer.mozilla.org/En/Using_web_workers - Using web workers
  • http://ejohn.org/blog/web-workers/ - Computing with JavaScript Web Workers
  • http://www.nczonline.net/blog/2009/08/18/experimenting-with-web-workers/ - Experimenting with web workers
  • http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html
  • http://developer.mozilla.org/en/docs/Canvas_tutorial
  • http://diveintohtml5.org/canvas.html - Dive into HTML 5
  • http://dev.w3.org/html5/html4-differences/
  • http://dev.w3.org/html5/markup/
  • http://www.whatwg.org/specs/web-forms/current-work/
  • http://www.cmswire.com/cms/web-content/html-5-supersedes-web-forms-20-004054.php
  • http://www.webmonkey.com/blog/HTML_5_Support_by_Browser - Google Wave
  • http://itknowledgeexchange.techtarget.com/overheard/html-5-the-browser-is-a-web-platform/

 

Resources URL: 
notes/html/resources
Sources URL: 
notes/html/sources

See Also