HTML5 Doctor » api http://html5doctor.com helping you implement HTML5 today Wed, 21 Jan 2015 14:57:35 +0000 en-US hourly 1 http://wordpress.org/?v=3.9.1 HTML5 Audio — The State of Play https://stevefaulkner.github.io/html5doctored/html5-audio-the-state-of-play/ https://stevefaulkner.github.io/html5doctored/html5-audio-the-state-of-play/#comments Tue, 08 May 2012 14:00:24 +0000 http://html5doctor.com/?p=4628 Guest doctor Mark Boas returns with a follow up to his 2009 article Native Audio in the Browser, which covers the basics of HTML5 audio. Read the original if you want to get a feel for the <audio> element and associated API. If not, get comfortable and dive deep to learn about the current state of play for HTML5 audio.

]]>
This is a follow up to my 2009 article Native Audio in the Browser, which covers the basics of HTML5 audio. It may well be worth reading if you want to get a feel for the <audio> element and associated API.

Now, two and a half years later, it’s time to see how things are progressing. With many new advanced audio APIs being actively worked on and plenty of improvements to the existing native audio we all know and love, it’s certainly an exciting time to revisit the heady world of <audio>.

A good way of understanding how the land lies is by going through a few use cases. That’s what I’ll attempt to do in this post.

So how do we get started? Well, there are a few things we need to do to prepare the ground. Let’s tackle MIME types first.

MIME Types

MIME types (also known as Internet Media Types) are a way of defining file formats so that your system knows how to handle them.

Server Side

First things first: your media server should be configured to serve correct MIME types. In the case of the Apache web server, this means adding the following lines to your .htaccess file:

# AddType TYPE/SUBTYPE EXTENSION
AddType audio/mpeg mp3
AddType audio/mp4 m4a
AddType audio/ogg ogg
AddType audio/ogg oga
AddType audio/webm webma
AddType audio/wav wav

Client Side

When defining sources in your code or markup, you can also specify the MIME type, which will help the browser identify the media correctly.

To set up HTML5 audio in the most robust manner, you could write something like this:

<audio>
   <source src="elvis.mp3" type='audio/mpeg; codecs="mp3"'>
   <source src="elvis.oga" type='audio/ogg; codecs="vorbis"'>
   <!-- add your fallback solution here -->
</audio>

Here we define the element and the sources to use. The browser will only pick one. It won’t play both. In this code, we also place a fallback solution after the <source> elements.

Along with the source, we specify a type attribute. Although not strictly necessary, this attribute allows the browser to know the MIME type and the codecs of the supplied media before it downloads it. If not, supplied the browser will guess and take a trial-and-error approach to detecting the media type.

Cool. So now we know how to define our audio sources, and the browser will happily pick the first source that it supports. But what if we want to supply the correct source in a more dynamic manner?

Knowing in Advance: canPlayType Can Help, Probably

Fortunately the audio API provides us with a way to find out whether a certain format is supported by the browser. But first, here’s a quick recap on how we manipulate the audio element via the API.

If you mark up your element in HTML as we did in our previous example, you can grab the <audio> element by doing the following:

var audio = document.getElementsByTagName('audio')[index];

// or, if you gave it an id attribute
var audio = document.getElementById('my-audio-id');

Alternatively, you can also create your element entirely in JavaScript:

var audio = new Audio();

Once you have your audio element, you’re ready to access its methods and properties. To test format support, you can use the canPlayType method, which takes a MIME type as a parameter:

audio.canPlayType('audio/ogg');

You can even explicitly include the codec:

audio.canPlayType('audio/ogg; codecs="vorbis"');

canPlayType returns one of three values:

  1. probably,
  2. maybe, or
  3. “” (the empty string).

The reason we have these odd return types is because of the general weirdness surrounding codecs. The browser can only guess at whether a certain codec is playable without actually trying to play it.

So to test for support, you could do this:

var audio = new Audio();
  var canPlayOgg = !!audio.canPlayType && audio.canPlayType('audio/ogg; codecs="vorbis"') != "";

All we’re doing here is checking that canPlayType is supported (!! effectively casts to a boolean) and then checking that canPlayType of our chosen format doesn’t return an empty string.

Current Browser Codec Support

Let’s check the codec support in the current crop of modern browsers.

Desktop browser audio codec support
Desktop Browser Version Codec Support
Internet Explorer 9.0+ MP3, AAC
Chrome 6.0+ Ogg Vorbis, MP3, WAV†
Firefox 3.6+ Ogg Vorbis, WAV
Safari 5.0+ MP3, AAC, WAV
Opera 10.0+ Ogg Vorbis, WAV

† WAV since Chrome 9

Mobile browser audio codec support
Mobile Browser Version Codec Support
Opera for Android 14.0+ Device-dependent††
Mobile Safari (iPhone, iPad, iPod Touch) iOS 3.0+ MP3, AAC
Android Stock browser 2.3+ Device-dependent††
Chrome for Android all Device-dependent††
Firefox for Android all Device-dependent††
Firefox OS ? ?
Windows Phone ? MP3, AAC
Blackberry 6.0+ MP3, AAC

†† mobile browsers generally use codecs on the host operating system. Various versions of Android include different codecs. Generally, mp3 and Ogg Vorbis can be assumed. See Supported Media Formats in official Android documentation for more.

The good news is that at the time of writing, it’s estimated that around 80% of browsers now support HTML5 audio.

The bad news is that there is still no consensus on which codec to support, so you’ll need to provide both MP3 and Ogg Vorbis sources in order to take full advantage of HTML5 audio.

Containers, Formats, and File Extensions (oh, and MIME types again)

Above, I’ve referred to the audio formats as they’re commonly known, but technically we should refer to their container format. (A container can contain more than one format — e.g., MP4 can contain AAC or AAC+.)

Container Format(s) File Extensions MIME Type Codec String
MP3 MP3 .mp3 audio/mpeg mp3
MP4 AAC, AAC+ .mp4, .m4a, .aac audio/mp4 mp4a.40.5
OGA/OGG Ogg Vorbis .oga, .ogg audio/ogg vorbis
WAV PCM .wav audio/wav 1

We have <audio> and we’re not afraid to use it!

Okay, we’ve done the minimum amount of work to get our audio element set up and playable. What else can we do? At the moment, we’re relying on the browsers’ default audio players, each of which looks and works a little bit differently than the rest. Perhaps we’d like to customise the experience and create our own. To help us do that, the <audio> element supports several different properties exposing its current state.

Some of the more commonly used properties:

Property Description Return Value
currentTime playhead position double (seconds)
duration media duration double (seconds); read-only
muted is volume muted? boolean
paused is media paused? boolean
volume volume level double (between 0 and 1)

Using these properties is pretty straightforward. For example:

var audio = new Audio();
var duration = audio.duration;

The variable duration now holds the duration (in seconds) of the audio clip.

Buffering, Seeking, and Time Ranges

The situation is improving in this area, as browser makers start to implement key parts of the spec.

The API provides attributes called buffered and seekable that can be used in situations where we want to ascertain which part of the media has been buffered, preloaded, or is ready to be played without delay.

Let’s first take a look at the buffered and seekable attributes. Both return a TimeRanges object. The TimeRanges object is a list of time periods containing start and end times that can be referenced by their indexes.

The buffered Attribute

The buffered attribute will return the time ranges that have been completely downloaded. A little bit of a code:

// returns TimeRanges object of buffered media
var buffered = audio.buffered;

// returns time in seconds of the last buffered TimeRange
var bufferedEnd = audio.buffered.end();

The TimeRanges Object

The TimeRanges object contains data on the parts on buffered media in the form of one or more — you guessed it — time ranges. A TimeRanges object consists of these properties:

  1. length — number of time ranges
  2. start(index) — start time in seconds of a particular time range
  3. end(index) — end time in seconds of a particular time range

You may be wondering in what situation the TimeRanges object would contain more than one time range. Imagine the user clicks forward to a portion of unbuffered media. The idea is that the media would then start buffering from that point, and you’d have two time ranges:

------------------------------------------------------
|=============|                    |===========|     |
------------------------------------------------------
0             5                    15          19    21

So in this case:

  • audio.buffered.length returns 2
  • audio.buffered.start(0) returns 0
  • audio.buffered.end(0) returns 5
  • audio.buffered.start(1) returns 15
  • audio.buffered.end(1) returns 19
  • audio.buffered.end() returns 19

Note that if the user is actively seeking through the media throughout the buffering process, a contiguous buffered progress bar actually makes little sense. Also consider that some browsers will read part of the end of the file to establish duration and so create two time ranges almost immediately. Now you’re starting to appreciate why making an accurate buffered progress bar is a little tricky!

You can check out TimeRanges in real-time using this handy HTML5 Media Event Inspector.

Seeking and Seekable

Seeking is the act of looking forward (or backward) in a media file. This usually happens when a section of media is requested before it’s finished loading.

The seeking attribute can be used to determine whether that part of the media is being actively “seeked”. When it returns true, the portion of the media the user requested is still being loaded.

To recap a little, the buffered property tells us what’s been downloaded and is often used as an indication of what part of the media can be directly played. If the browser supports it, however, it may make more sense to use the seekable attribute to determine which parts of the media can be jumped to and played immediately.

seekable returns a TimeRanges object of time ranges that can be played immediately. This uses a technology known as byte-range requests, which allows part of the content to be requested over HTTP. In short, we don’t have to load all the data prior to the desired part in order to play it.

An example:

// Is the player currently seeking?
var isSeeking = audio.seeking;

// Is the media seekable?
var isSeekable = audio.seekable && audio.seekable.length > 0;

// Time in seconds within which the media is seekable.
var seekableEnd = audio.seekable.end();

Time ranges can be confusing. audio.seekable.end() actually tells us the end point of the last time range (not the end point of all seekable media). In practice, though, this is good enough, as the browser either enables range requests or doesn’t. If it doesn’t, then audio.seekable will be equivalent to audio.buffered, which will give a valid indication of the end of seekable media.

Note that media being in a “seekable” state is different than media being in a “buffered” state. Media doesn’t have to be buffered to be seekable.

Buffered and seekable data can be useful information, but it would be too easy if there weren’t a few gotchas.

  1. Preloading is not supported in all older audio-capable browsers (Opera 10/Firefox 3.6).
  2. The buffered attribute is not always supported (Blackberry PlayBook).
  3. Not all HTML5 browsers allow byte-range seeking — for example, Safari on Windows. In this case, you can still seek within the downloaded content. It downloads from the start until the end, as does Flash.

If you want to deliver the best possible solution to your users, you’ll need to feature test.

A Note about Preloading

I mentioned the preload attribute in the previous article. This attribute accepts three possible values:

  1. none — Do not preload any media. Wait for a play event before downloading anything.
  2. metadata — Preload just the metadata. Grab the start and the end of the file via range-request and determine the duration.
  3. auto — Preload the whole file. Grab the start and the end of the file to determine duration, then seek back to the start again for the preload proper.

When it comes to preloading, remember that it’s a request or hint to tell the browser how you’d like to preload the media. The browser is not under any obligation to fulfill that request. For this reason, certain browsers may handle these requests differently.

Well-Played

It’s worth mentioning the played property in passing. This property tells us which time ranges have been played within the media. For example:

// returns a TimeRanges object
var played = audio.played;

Media Events

Underpinning both the native audio and video APIs is a comprehensive set of events. A full list can be found at the WhatWG version of the spec.

Attaching handlers to media events allows you to easily react to changes in state. For example, it might be useful to update the time info in a custom-built player each time the timeupdate event occurs.

A quick summary of the more commonly used media events:

Event Description
durationchange The duration attribute has been updated.
ended Playback has stopped as the end of the media was reached.
pause The media playback has been paused. Note there is no stop event.
play The media has started playing.
timeupdate The current playback position changed (usually every 250ms).
volumechange The volume changed.

Other useful events:

Event Description
canplay The media can be played but may need to pause while the file is downloaded.
canplaythrough At current download rates, it is estimated that the media can be played from start to finish without pause.
progress The browser is fetching the media data (usually every 250ms).

Again, the HTML5 Media Event Inspector is your friend.

Additionally, you can test browser support by using areweplayingyet.org. It’s worth checking out the code behind the tests to understand the goings-on under the hood.

Streaming

Streaming audio is a common requirement. This is an area that until recently has been dominated by Adobe’s Flash technology. Proprietary server technologies and protocols are well-established. One of the leading examples of this is Adobe’s Real Time Messaging Protocol (RTMP). However, current browsers only support streaming over HTTP, and so something like Flash is required to process RTMP streams.

Currently, audio-enabled browsers only support SHOUTcast and Icecast servers that stream audio over HTTP. SHOUTcast is propriety and allows streaming of MP3 and AAC files only, while Icecast is non-propriety and supports Ogg Vorbis as well as MP3 and AAC.

Stream AAC MP3 Ogg Vorbis Native Support
Icecast Yes Yes Yes Yes
SHOUTCast Yes Yes No Yes
RTMP Yes Yes No No (requires Flash)

An Evolving Spec (Or, “Whoa, this thing is moving!”)

As the audio spec is still evolving, there are a couple of inconsistencies in browser implementations to watch out for. These generally affect older browsers.

The load Method

Until fairly recently, the load method was required in order to tell the browser about a change in the media source and to get it to update appropriately. Now, media.load() causes the element to reset and to start selecting and loading a new media resource from scratch.

So for older browsers, such as Firefox 3.6, in order to change the media source, you’ll not only need to change the source value but also issue a load command:

var audio = new Audio();
audio.setAttribute("src","mynew.mp3");
audio.load(); // required for 'older' browsers

When Browsers Go Off-Spec

When creating cross-browser solutions, it’s useful to know which browsers follow the W3C spec to what extent and how they deviate.

Autoplay and Volume

iOS and Blackberry devices ignore the autoplay attribute and media element volume changes, whereas Android supports autoplay but not volume changes.

Effectively, on Blackberry and iOS devices, autoplay functionality is disabled as both require a user-initiated event to “kick it off”. This has the unfortunate side-effect that any audio suffers a delay between user interaction and playback.

To mitigate against these issues, you may want to take a look at Doctor Remy Sharp’s excellent article on Audio Sprites and fixes for iOS.

Simultaneous Playback of Multiple Audio Elements

A particular annoyance for developers of anything but the most simple audio web apps: not all browsers will play multiple audio elements simultaneously. This is a particular problem for games developers. Again, we see this issue with iOS and Blackberry devices.

Operating System Dependence

Safari (5+) relies on Quicktime being installed. This is rarely a problem unless you are running it on Windows.

Internet Explorer (9+) relies on the codecs being present at the operating system level. As it only runs on Windows, this is fortunately almost always the case.

What’s New?

There are a few new features and whole new APIs being specified for web-based audio, so let’s take a look at what’s around the corner.

A Change of Pace

A couple of noteworthy upcoming features are playbackRate and defaultPlaybackRate. As you can probably imagine, these fellas let us alter the speed and direction of playback. This functionality could be used for fast-forward and rewind functions or perhaps to allow users to tweak the playback speed so they can fit more podcasts into their day.

  • audio.playbackRate returns 1 at normal speed and acts as a multiple that is applied to the rate of playback. For example, setting playbackRate to 2 would double the speed, while setting it to -1 would play the media backwards.
  • audio.defaultPlaybackRate is the rate at which the audio will play after you pause and restart the media (or issue any event for that matter).

Media Fragments

Currently, if we wish to reference some part of a media file, we often first have to download at least some of the media we don't actually need. The W3C Media Fragments proposal was created to address this issue and others, such as the retrieval of an area of video or just the associated text track. In the case of audio, it will allow us to specify which parts we want to download using parameters on the source URI.

Advanced Audio APIs: The Future Sound of Browsers

When it comes to more advanced audio functionality, Mozilla was first to enter the fray with an early experimental Audio Data API for Firefox. This was intended to facilitate audio manipulation via JavaScript and created a platform for low-level tinkering.

Not to be outdone, Google released the Web Audio API for Chrome and put it forward as a W3C proposal. The Web Audio API is a higher-level implementation that takes an audio-node based approach and provides many useful functions.

Both implementations address the desire by developers to do more with audio — to create, manipulate, analyse, and mix audio on the fly. In effect, we may one day be able to do in a browser anything we can currently do with native applications.

So what if we want to play with advanced audio in the browser? Well, two separate implementations currently exist. If you want to write applications that use both APIs in any reasonable way, you need third-party bridging libraries to abstract away the differences.

Also fairly new on the scene is Mozilla's MediaStream Processing API, which takes another approach to audio and video streams to allow us to manipulate at both high and low levels.

In fact, using advanced APIs and taking advantage of the speed of modern JavaScript engines, we can even write decoders for unsupported codecs. Currently, we have the JSMad MP3 decoder and the lossless Alac.js decoder. Apparently, FLAC and AAC are in the pipeline. There is hope, then, that in the future, we may not have to worry about which browsers are supporting which formats.

For those curious about advanced web audio, I wrote about the differences in approaches and the different libraries that allow us to write cross-browser solutions in HTML5 Audio APIs: How Low can we Go?

The good news is that all relevant parties are talking, and things seem to be buzzing on the W3C Audio Working Group. It looks like everyone is coming together to put their ideas into a unified Audio Processing API, which is rapidly approaching publication as a Web Standard.

Summary

Although browser implementations of the current HTML5 audio spec are improving, there are still a few issues to watch out for when creating comprehensive cross-browser solutions. You certainly need to be aware of browser limitations on platforms like iOS. Hopefully, as support matures, these issues will disappear.

Positive news on the "advanced audio" front too: a new standard is being established, and we're close to get a unified spec for browser makers to work from. In the meantime, JavaScript libraries are available to help bridge the gaps between existing implementations.

There are also signs that we may be seeing the end of the requirement for different browser-dependent codecs. Opera Mobile already supports MP3 where the underlying OS supports it, and Mozilla look like they may enable this too. If this option exists for mobile browsers, it's not a huge stretch to imagine that desktop browsers will follow suit.

So lots happening and lots already achieved. The rough edges of existing browser implementations are being smoothed, consensus and standards are being forged, and we can see the foundations of some very exciting new technologies being established.

The future of web-based audio looks bright!

HTML5 Audio — The State of Play originally appeared on HTML5 Doctor on May 8, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/html5-audio-the-state-of-play/feed/ 31
Drag and Drop and Automatically Send to the Server https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/ https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/#comments Tue, 03 Apr 2012 13:30:17 +0000 http://html5doctor.com/?p=4500 I realised (when looking myself) that there are a lot of demos and tutorials that show you how to drag-and-drop a file into the browser and then render it on the page. They're often labelled as "drag-and-drop and upload", but they actually don't upload. This tutorial will take you that final step.

]]>
I realised (when looking myself) that there are a lot of demos and tutorials that show you how to drag-and-drop a file into the browser and then render it on the page. They're often labelled as "drag-and-drop and upload", but they actually don't upload. This tutorial will take you that final step.

I'll walk you through an example that you can play with: drag a file into the web page, and it'll be uploaded to the server instantly.

Tasks

Let's break this process down into specific tasks:

  1. Capture the drop event and read its data.
  2. Post that binary data to the server.
  3. Provide feedback on the progress of the upload.
  4. Optionally render a preview of what's being uploaded and its status.

To achieve all of this, we need the following HTML5 and non-HTML5 APIs:

  1. Drag and Drop
  2. FormData
  3. XHR progress event
  4. FileReader

Keep in mind that not all browsers support all of this technology today, but they're getting close. I just wanted to create a clear and complete tutorial on how to go the whole hog and upload that dropped file.

The end result: we're able to drop the file anywhere in the browser, we get a preview and progress of the upload, and it's a slick experience.

Drag and drop upload
Our drag-and-drop example page

Drag and Drop

Just as a forewarning, drag-and-drop has been known to be a bit of a killjoy. In fact, it's a nightmare, but I won't repeat what's been said before.

Our example is going to allow you to drag-and-drop a file anywhere within the browser. To achieve that, we need to attach our event listeners to the body or documentElement (i.e., the root HTML node). By listening on the documentElement, this code could be anywhere in the page, as documentElement will always exist. You can only listen on body once the <body> element has been encountered.

Here's the pattern of code we need to capture the drop event on the entire document:

var doc = document.documentElement;
doc.ondragover = function () { this.className = 'hover'; return false; };
doc.ondragend = function () { this.className = ''; return false; };
doc.ondrop = function (event) {
  event.preventDefault && event.preventDefault();
  this.className = '';

  // now do something with:
  var files = event.dataTransfer.files;

  return false;
};
Basic pattern for capturing drop events

I'm using the hover class so that I can toggle a tip explaining to the user that the file can be dropped on the page.

Inside the drop event, we can access the dropped files via event.dataTransfer.files.

An Alternative to Drag and Drop

Annoyingly, as I write this, I realise this combination of API requirements is currently only met by Chrome and Firefox. So, taking the test from Modernizr, we can test for support and provide our alternative:

var dndSupported = function () {
  var div = document.createElement('div');
  return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
};

if (!dndSupported()) {
  // take alternative route
}
Testing for drag-and-drop support

Instead of drag-and-drop, we can insert a file input element (I've given it an id of "upload"), and when its value is changed, the file can be scooped in:

document.getElementById('upload').onchange = function (event) {
  // `this` refers to the element the event fired upon
  var files = this.files;
};
An alternative to native drag-and-drop

You can see the equivalent is simply the files property of the HTMLInputElement object. This will give us access to the same file as the event.dataTransfer.files from the drop event.

Automatically Uploading the File

This is the neat bit, and it's painfully simple. We use a feature of the XHR2 spec: FormData. Once we create an instance of FormData, we can append items to it:

var formData = new FormData();
for (var i = 0; i < files.length; i++) {
  formData.append('file', files[i]);
}

// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', '/upload');
xhr.onload = function () {
  if (xhr.status === 200) {
    console.log('all done: ' + xhr.status);
  } else {
    console.log('Something went terribly wrong...');
  }
};

xhr.send(formData);
Creating and posting FormData

Yeah, that's it.†

Let's look at a couple of key things that are going on the above code.

formData.append('file', files[i]);

We're sending named parameters to our server, specifically an array of values called file. Obviously, you can call it what you want, but the file is the name your server will be looking for when it saves the uploaded file (or files).

xhr.onload = function () {
  if (xhr.status === 200) {
    console.log('all done: ' + xhr.status);
  } else {
    console.log('Something went terribly wrong...');
  }
};

If you're familiar with XHR, you'll notice we aren't listening to onreadystatechange, only onload — which is (in effect) a convenience function to let you know when the readyState is 4 (i.e., loaded!). You should still check and respond appropriately to the status code of the request to ensure it's 200 OK, rather than a 500 (internal server error) or 404 (not found) or anything else.

xhr.send(formData);

The nice trick here is that XHR has automatically set the encoding of the posted data to multipart/form-data. This encoding allows your server to read and save the files. It's like the encoding used when you send an attachment in an email.

Providing Feedback to the User

XHR2 now (flippin' finally) comes with a progress event. So if you're sending or retrieving a large file via XHR, you can tell the user how far along you are.

It's pretty simple. If you want to track the progress of the XHR request, listen to the progress event. One gotcha that caught me out for some time: I needed to track the progress of the upload, not the download. To do this properly, you need to listen for progress on the XHR upload object, as so:

xhr.upload.onprogress = function (event) {
  if (event.lengthComputable) {
    var complete = (event.loaded / event.total * 100 | 0);
    progress.value = progress.innerHTML = complete;
  }
};

xhr.onload = function () {
  // just in case we get stuck around 99%
  progress.value = progress.innerHTML = 100;
};
Providing feedback with XHR2's progress event

Note that instead of xhr.onprogress, we use xhr.upload.onprogess. When this event fires, we check that the event supports calculating the amount of data uploaded (the lengthComputable part), and then calculate the amount completed.

In my HTML, I'm using a <progress> element (similar to the <meter> element, but more semantically appropriate as we're presenting the progress of a task) to show the user how much of their file has been uploaded:

<progress id="progress" min="0" max="100" value="0">0</progress>

Note that I'm using innerHTML for browsers that don't yet support <progress>. Then with a dash of CSS-generated content, both the innerHTML and value of the progress can be the same (perhaps an over optimisation, but I was rather proud of myself at the time!).

And Finally, Rendering a Preview

As a nice addition, we'll give the user a preview of what we're uploading for them. It requires the File API — specifically the FileReader API.

As the drag-and-drop operation (or the input[type=file]) contains a file object, we can hand this over to the FileReader to get the contents of the file. If it's something like an image, we can get the Base64 data and give the user a preview. Or if it's text, we could render it in a <div>. The MIME type for the file is available as the type property on the file object.

So let's assume we only accept images. Here's the preview part that runs after the file has been received by the browser:

var acceptedTypes = {
  'image/png': true,
  'image/jpeg': true,
  'image/gif': true
};

if (acceptedTypes[file.type] === true) {
  var reader = new FileReader();
  reader.onload = function (event) {
    var image = new Image();
    image.src = event.target.result;
    image.width = 100; // a fake resize
    document.body.appendChild(image);
  };

  reader.readAsDataURL(file);
}
Rendering a preview of an uploaded image

We create the FileReader and give it a file to read. In the above example, I've used readAsDataURL, but you can also read files in plain text and binary formats (as per the spec).

When the reader has read the file and the data is available, it fires the load event, which in turn creates our new image.

The result of the file read action is in the event.target.result property. In the case of the readAsDataURL, the value is along the lines of data:image/png;base64,ABC....

Using All the Tools in the Shed

This example may be a little contrived for the article that I wanted to write. I've used many different technologies to do something that's a fairly common pattern on the web. In fact, it was because I had trouble finding a definitive source on uploading to the actual server (except, of course, as I wrote this article I found this example from back in late 2010!).

Hopefully, you'll see how each bit of tech can work together to create an application, but equally I hope that you can see where this would work if none or just some of the technology wasn't available. Make sure you detect functionality. Make sure you provide fallbacks. Make sure you develop responsibly.

Here's the final drag-and-drop and upload demo for you to play with.

Drag and Drop and Automatically Send to the Server originally appeared on HTML5 Doctor on April 3, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/drag-and-drop-to-server/feed/ 40
Server-Sent Events https://stevefaulkner.github.io/html5doctored/server-sent-events/ https://stevefaulkner.github.io/html5doctored/server-sent-events/#comments Tue, 24 Jan 2012 14:30:33 +0000 http://html5doctor.com/?p=4181

Related Posts:

]]>
We’ve already had a glimpse at Server-Sent Events (also known as EventSource†, and I’ll switch between the two to keep you on your toes) in my Methods of Communication article from last year. In this article, I want to delve in to more detail about the SSE API, demonstrate its features, and even show you how to polyfill browsers that lack EventSource support.

Server-Sent Events are real-time events emitted by the server and received by the browser. They’re similar to WebSockets in that they happen in real time, but they’re very much a one-way communication method from the server.

These events are similar to ordinary JavaScript events that occur in the browser — like click events — except we can control the name of the event and the data associated with it.

All the code for this article is available on github, and a live demo is available online.

† Is it Server-Sent Events or EventSource? Well, they both work. Server-Sent Events is the name of the API and specification. EventSource is the name of the JavaScript object you’re instantiating. It’s a bit like Ajax and XHR, where XHR refers to the XMLHttpRequest object…kinda.

Two notes: a) the uptime for this example is, I’m afraid, usually rather low — good for my server, bad for you. If you test the demo locally it will give you more interesting figures. b) IE6 isn’t supported in any of this article.

Possible Applications

A few simple examples of applications that could make use of Server-Sent Events:

  • A real-time chart of streaming stock prices
  • Real-time news coverage of an important event (posting links, tweets, and images)
  • A live Twitter wall fed by Twitter’s streaming API
  • A monitor for server statistics like uptime, health, and running processes

We’ll use the server monitor for this article’s examples. If this application were to be used in the wild, we could also check the EventSource‘s connection state to indicate when there’s a potential problem connecting to the server.

Overview of the API

The client-side API is rather simple, and it hands-down beats the insane hacks required to get real-time events to the browser back in the bad old days.

The main points of interest:

  • new EventSource(url) — this creates our EventSource object, which immediately starts listening for events on the given URL.
  • readyState — as with XHR, we have a readyState for the EventSource that tells us if we’re connecting (0), open (1), or closed (2).
  • onopen, onmessage — two events that we can listen for on the new EventSource object. By default, the message event will fire when new messages are received, unless the server explicitly sets the event type.
  • addEventListener — not only can we listen for the default message event, but we can also listen for custom messages using the addEventListener on the EventSource object, just as if we were listening for a click event.
  • event.data — as with most messaging APIs, the contents of the message reside in the data property of the event object. This is a string, so if we want to pass around an object, we need to encode and decode it with JSON.
  • close — closes the connection from the client side.

In the future, EventSource will also support CORS using an options argument to the EventSource object: { withCredentials: true }. But at the time of writing, no stable release includes this property.

Simple Example

Our simple web app will notify us of server status messages — things like the load average, number of currently connected users, and most CPU-intensive processes. If I were using this application in anger, I’d probably build server modules that emit specific event types when they cross specific thresholds, so that I’m only notified when something gets to warning level.

This snippet of JavaScript connects to our server, listens for messages, and handles the data that comes with the messages:

var source = new EventSource('/stats');
source.onopen = function () {
  connectionOpen(true);
};

source.onerror = function () {
  connectionOpen(false);
};

source.addEventListener('connections', updateConnections, false);
source.addEventListener('requests', updateRequests, false);
source.addEventListener('uptime', updateUptime, false);

source.onmessage = function (event) {
  // a message without a type was fired
};

Properties of Server-Sent Events

Server-Sent Events are more than just a one-way web socket. They have some unique features:

  • The connection stream is from the server and read-only. This suits lots of applications, some examples of which I listed above.
  • They use regular HTTP requests for the persistent connection, not a special protocol, which means we can polyfill using vanilla JavaScript.
  • If the connection drops, the EventSource fires an error event and automatically tries to reconnect. The server can also control the timeout before the client tries to reconnect.
  • Clients can send a unique ID with messages. When a client tries to reconnect after a dropped connection, it will send the last known ID. Then the server can see that the client missed n messages and send the backlog of missed messages on reconnect.

Message Format

A simple message doesn’t require much:

data: this is a simple message
<blank line>

Note that the end of a message is indicated by a blank line (obviously not the literal characters <blank line>).

For a message with multiple lines:

data: this is line one
data: and this is line two

You can send message IDs to be used if the connection is dropped:

id: 33
data: this is line one
data: this is line two

You can even send multiple messages in a single response so long as you separate the messages by blank lines:

id: 34
data: Remy is awesome

id: 35
data: Bruce is stinky

And you can specify your own event types (the above messages will all trigger the message event):

id: 36
event: price
data: 103.34

id: 37
event: news
data: Bruce sells his collection of replica bananas

You don’t have to worry about this structure on the client side. It only applies to the server, which I’ll touch on next.

Typical Server

I’m not going to give a full walkthrough of the server-side code, since this is an HTML5 web site :) But there are a few important and simple features that you need to know to build the server (you’ll need this part anyway if you’re going to use EventSource).

I’ve included all the files for this demo on GitHub for you to peruse at your own leisure, and I’ve also deployed a live example of this code.

Ideally, you should use a server that has an event loop. This means you should not use Apache, but instead use a platform such as Node.js (which I’ve used) or Twisted for Python.

Key properties:

  1. You can only accept EventSource requests if the HTTP request says it can accept the event-stream MIME type.
  2. You need to maintain a list of all the connected users in order to emit new events.
  3. You should listen for dropped connections and remove them from the list of connected users.
  4. You should optionally maintain a history of messages so that reconnecting clients can catch up on missed messages.

Here’s a sample of my Node.js based server. It’s using Connect (a simple webby framework for Node). When it receives a request for /stats, it calls the following function. I’ve commented the code so you can follow along:

function stats(request, response) {
  // only response to an event-stream if the request 
  // actually accepts an event-stream
  if (request.headers.accept == 'text/event-stream') {

    // send the header to tell the client that we're going
    // to be streaming content down the connection
    response.writeHead(200, {
      'content-type': 'text/event-stream',
      'cache-control': 'no-cache',
      'connection': 'keep-alive'
    });

    // support the polyfill - we'll come on to this later
    if (request.headers['x-requested-with'] == 'XMLHttpRequest') {
      response.xhr = null;
    }

    // if there was a lastEventId sent in the header, send
    // the history of messages we've already stored up
    if (request.headers['last-event-id']) {
      var id = parseInt(request.headers['last-event-id']);
      for (var i = 0; i < history.length; i++) {
        if (history[i].id >= id) {
          sendSSE(response, history[i].id, history[i].event, history[i].message);
        }
      }
    } else {
      // if the client didn't send a lastEventId, it's the
      // first time they've come to our service, so send an
      // initial empty message with no id - this will reset
      // their id counter too.
      response.write('id\n\n');
    }

    // cache their connection - the response is where we write
    // to send messages
    connections.push(response);

    // send a broadcast message to all connected clients with
    // the total number of connections we have.
    broadcast('connections', connections.length);

    // if the connection closes to the client, remove them
    // from the connections array.
    request.on('close', function () {
      removeConnection(response);
    });
  } else {
    // if the client doesn't accept event-stream mime type,
    // send them the regular index.html page - you could do
    // anything here, including sending the client an error.
    response.writeHead(302, { location: "/index.html" });
    response.end();
  }
}

The important trick on the server is to ensure you don’t close the connection to the EventSource object. If you do, it will of course handle the closed connection, fire an error event, and try to reconnect. So you’ll just want to maintain the persistent connection.

Polyfills and Tweaks to the Server

There are two good polyfills I know of, and though I prefer the one I wrote, I’ll still lay them both out for you.

Yaffle’s Polyfill

The first is one by Yaffle (on github), available on github/Yaffle/eventsource.

The cons:

  • It doesn’t send the accepts header, and
  • It completely replaces the EventSource object, so even if your browser supports EventSource natively, this script will replace it. But there’s a good reason for that.

The pros:

  • It maintains a persistent connection (whereas the one we’re using doesn’t), and
  • More interestingly, it supports CORS (which I imagine is why it replaces the native EventSource).

These two pros are quite compelling. But when I was testing, I couldn’t get it working in IE7 (which was my minimum browser target), so that might be a blocker for you…or not.

Remy’s Polyfill

The second is my own, available on github.com/remy/polyfills.

The cons:

  • It uses polling, so once a small group of messages come down, it re-establishes the connection, which could lead to significant overhead (though less so on a Node-based server). You have to add about 4 extra lines to your server code.

The pros:

  • It doesn’t replace the native EventSource object (but that also implies that, for now, it won’t support CORS), and
  • It supports IE7.

Retrospectively, I might choose Yaffle’s polyfill over mine in the future if I wasn’t bothered about IE7 support.

Using the Polyfill

By including the EventSource.js JavaScript library before my client-side code, I just need a couple of small changes to my server-side code. Other than that, everything on the client side works without any changes (as a polyfill should work).

When posting the server’s reply to the client, instead of keeping the connection open, I include the following in my server when it’s finished writing the response:

// send the data (event type, id, message, etc)
response.write(data);

// if our response contains our custom xhr property, then...
if (response.hasOwnProperty('xhr')) {
  // clear any previous timers using the xhr prop as the value
  clearTimeout(response.xhr);

  // now set a timer for 1/4 second (abritrary number) that
  // then closes the connection and removes itself from the
  // connection array.
  // The delay is in place so that a burst of messages can 
  // go out on the same connection *before* it's closed.
  response.xhr = setTimeout(function () {
    response.end();
    removeConnection(response);
  }, 250);
}

Bugs?

The error event should always fire when the readyState changes, assuming you didn’t explicitly call the close method. This works nearly all the time, but in writing this article, I found a few edge cases where it doesn’t fire. In Chrome, if I put my machine to sleep and then woke it back up, it would close the connection but not fire the event, therefore never triggering a reconnection. As I said, this is an edge case and I’ll file a bug against it, so I don’t expect it to hang around for long.

Why Not Use WebSockets?

There are two reasons I’d advocate using EventSource over WebSockets, as they’re currently the two contenders for sending real-time events to the browser.

The first is that EventSource (as we saw earlier) works over regular HTTP and can therefore be replicated entirely using JavaScript if it’s not available natively. That means that we can polyfill browsers without support, like IE9.

The second is probably more important: you should always use the right technology for the job. If your real-time data is sourced from your web site, and the user doesn’t interact in real-time, it’s likely you need Server-Sent Events.

I recently saw a cool demo of snowflakes drifting down a web site. Each snowflake is a tweet based around the Christmas theme — like if someone mentions a particular Christmas-y term, it’s sucked in to the snowflake. Don’t get me wrong, I know this is a demo, and it’s very cool (if you wrote it, this is me sending you hugs), but it’s based on WebSockets. I’d suggest this demo should be based on EventSource since all the data is read-only and the user doesn’t interact with it at all.

The point: evaluate the technology against your problem, and aim to get good fit.

Server-Sent Events originally appeared on HTML5 Doctor on January 24, 2012.

]]>
https://stevefaulkner.github.io/html5doctored/server-sent-events/feed/ 51
Pushing and Popping with the History API https://stevefaulkner.github.io/html5doctored/history-api/ https://stevefaulkner.github.io/html5doctored/history-api/#comments Tue, 15 Nov 2011 13:09:47 +0000 http://html5doctor.com/?p=3897

Related Posts:

]]>
Until recently, we developers couldn’t to do much with the state and history of the browser. We could check the number of items in the history and push users forwards and backwards, but this provides little benefit to the user. With the rise of more dynamic web pages, we need more control. Thankfully, HTML5 gives us that control by extending the JavaScript History API.

What’s the point?

It goes without saying that URLs are important. They’re the method of accessing the vast collections of information and resources on the web, and more recently, they’ve begun representing the intended state of a web application. You can copy these URLs and share them with your friends or use them to create links from any HTML document. They’re the veins of the web, and they need to be looked after.

Previously, the JavaScript History API offered some very simple functionality:

// Check the length of the history stack
console.log(history.length);

// Send the user agent forward
console.log(history.forward());

// Send the user agent back
console.log(history.back());

// Send the user agent back (negative) or forward (positive)
// by a given number of items
console.log(history.go(-3));

With dynamic Ajax web applications, where the browser updates the page in parts instead of changing location entirely, it’s difficult to give the user a URL to bookmark or share the current application state. Fragment identifiers, like those used on this article’s headings via the id attribute, provide some state information, but they’re entirely dependent on client-side scripts.

The changes to the History API are intended to give developers ways to push history items to the browser so the native back and forward actions can cycle through those items. These history items can also hold data that you can later extract to restore the page state.

Pages can add state objects between their entry in the session history and the next (“forward”) entry. These are then returned to the script when the user (or script) goes back in the history, thus enabling authors to use the “navigation” metaphor even in one-page applications.

If the user copies or bookmarks a stateful URL and visits it later, your back-end can be configured to interpret such a URL and jump the user right to the correct page and/or state.

In this article, I’ll cover the client-side use of the History API, so make sure you set up your server to work with the new URLs. If you’ve already built an accessible website that provide these entry points, you’re laughing!

Those f#!king hashbangs…

You may have already seen articles fussing over the adoption of the “hashbang” (#!) pattern on sites like Twitter. This technique updates the address bar with a fragment identifier that can then be used by JavaScript to determine which page and state should be displayed.

This works as a method of creating a bookmarkable, shareable URL for a page’s state in the absense of a standard API. While the Twitter implementation accepts both http://twitter.com/#!/akamike and http://twitter.com/akamike, it has some disadvantages:

  • The fragment identifier is only accessible on the client side. This means that only JavaScript can utilise it, so browsers without JavaScript enabled are out of luck.
  • As the server does not receive the path following the hashbang, removing that JavaScript drops support for all those URLs. That’s a lot of broken links, so you’re stuck with that JavaScript forever.
  • It’s ugly. It’s a hack and it looks like one.

The hashbang was never intended to be a long-term solution, so don’t rely on it. If you do use hashbangs, be prepared to deal with the consequences (and possible backlash from web purists).

Making History

These examples will build on top of each other. We’ll start with a basic HTML document with some inline styles and scripts for your convenience.

Save this file and open it in your favourite editor. It must be accessed via HTTP, so that means you need either a local server (e.g. http://localhost/) or an online web server you can upload to. Viewing the file directly using your browser’s Open File function will not work, since it uses the file:// protocol and not HTTP. Also be sure to update the href attributes on each of the navigation links to ensure the correct directory structure is used. Personally, I’m viewing the demo locally at http://localhost/history.

We’ll be working exclusively within the <script> element at the end of the <body>. The code includes some simple styles and dynamically changes the content as you click the links. In reality, this could be loaded from your server via XMLHttpRequest, but for the purposes of this demonstration I’ve bundled it up into a self-contained file. The important part is that we have a quick-and-dirty dynamic page to work with, so let the fun begin!

At the moment there, is no bookmarkable URL for the different states of this page. If you click around the navigation items, then click Back in your browser, you won’t be taken back to the previous state and may even be taken away from the page to whatever you viewed before (depending on your browser). It would be nice if you could share “Socks” with your friends, right? We can do that via history.pushState().

The history.pushState() method takes three parameters:

data
Some structured data, such as settings or content, assigned to the history item.
title
The name of the item in the history drop-down shown by the browser’s back and forward buttons. (Note: this is not currently supported by any major browsers.)
url (optional)
The URL to this state that should be displayed in the address bar.

With these parameters, you can define the state of the page, give that state a name, and even provide a bookmarkable address, as if the page had reloaded entirely. Let’s dive right in and add this to the clickHandler function, right above the return statement:

function clickHandler(e) {
  /* Snip... */

  // Add an item to the history log
  history.pushState(data, event.target.textContent, event.target.href);

  return event.preventDefault();
}

The single line of code we added informs the history object that:

  • we want to add an item to the log,
  • it should remember the data that we’ve already loaded,
  • it should assign a name to this state based on the text of the link we clicked (even though this isn’t used — it’s good to get into the habit of recording a name for the state), and
  • it should update the address bar with the href attribute of that link.

Reload the page in your browser and click a few of the links, keeping an eye on the address bar. Notice how it changes on each click, despite the fact that you aren’t actually navigating away from this page. If you also have a look at your history log, you’ll see a long list of page titles (in this case ”Kittens!” over and over). Provided your server is set up to serve the correct page upon access, the user could copy that URL and paste it into a new browser window to jump straight to that kitten.

At the moment, clicking the back button will pop you through the history items, but the page won’t react to these changes. That’s because so far, we’ve only created the history records. How can we allow active users to return to a previous state? We listen to the popstate event.

Historical Events in Navigation

The user agent fires a popstate event when the user navigates through their history, whether backwards or forwards, provided it isn’t taking the user away from the current page. That is, all those pushStates we called will keep the user on the current page, so the popstate event will fire for each history item they pop through.

Before the closing </script> tag, add a new listener for the popstate event:

// Revert to a previously saved state
window.addEventListener('popstate', function(event) {
  console.log('popstate fired!');

  updateContent(event.state);
});

We attach the event listener to the window, which is responsible for firing the event, and pass this event into our handler. We log a message (so we can see when this event is firing), and then we update the content using the state we saved previously. The state is attached to the event object via the state property.

Open up the page fresh in your browser, click around like before, and then click back. As before, the URL in the address bar changes as you cycle through states, but now the content is also restored back to what it should be. Click forward, and the content is likewise correctly restored.

If you look at the developer console in Chrome when you load the page for the first time, you’ll see the popstate event fired immediately, before you’ve even clicked a link. This is because Chrome considers the initial page load to be a change in state, and so it fires the event. In this instance, the state property is null, but thankfully the updateContent function deals with this. Keep this in mind when developing as it could catch you out, especially if other browsers assume this behavior.

Rewriting history

Unfortunately, as fantastic as HTML5 is, it doesn’t allow us actual time travel. If it did, I would be going back to my childhood and telling a younger me, “Yes, you should have a slice of cake”. Take that as you will.

The History API does, however, allow us to make amends to our history log items. For example, we could update the current state in response to fresh user input in a form. We can do this with history.replaceState.

replaceState works just as pushState does, with the exact same parameters, except that it updates the current entry instead of adding a new one. I can think of one situation in our demo where this could be used: the initial page load. If you click back for long enough, you’ll find that going back to the original URL doesn’t provide you the original content. Let’s fix that by adding the following to the bottom of our script:

// Store the initial content so we can revisit it later
history.replaceState({
  content: contentEl.textContent,
  photo: photoEl.src
}, document.title, document.location.href);

As this runs when the page loads, it saves the initial page state. We can later load this state when the user browses back to this point via the event listener we set up previously. You can try it out by loading up the page, clicking a few links, and then hitting back until you return to the original URL. The initial content has returned!

Demo

I’ve set up a demo of our completed code. I’ve also added a little back-end magic to make our history.pushState URLs work like a real site. Remember that the URLs you push should be live URLs that the user can bookmark and share as real entry points to your site.

View the History API demo

Browser support

Up-to-date copies of Chrome (5+), Safari (5.0+), Firefox (4.0+), and Opera (11.50+) have support for the new History API. Even some mobile browsers work just fine, like Mobile Safari on iOS 4+. Unfortunately, IE 9 and below lack support, but it should work in IE 10 when it arrives.

Safari 5.0 sometimes exhibits one oddity: navigating between states causes the loading spinner to appear and stay even when the state has been loaded. This stops when you navigate away using a link or action that does not involve a state saved by the History API.

Polyfill

A polyfill does exist for the History API. The aptly named History.js uses HTML4’s hashchange event with document fragment identifiers to mimic the history API in older browsers. If one of the hash URLs is used by a modern browser, it uses replaceState to quietly correct the URL.

It sounds like magic, but make sure you’re aware of the consequences of using fragment identifiers, as mentioned previously in this article. As such, the author of History.js has put together a guide titled Intelligent State Handling.

Closing thoughts

URLs go beyond just the browsing session of a user. They’re historically important markers for resources that could very well remain in use for many years to come. Before you embark on developing your site’s JavaScript, you should give thought to the design of your URLs. Make them meaningful and organised. Make sure you can directly access them without JavaScript. Only then should you add your JavaScript to enhance the browsing experience.

Pushing and Popping with the History API originally appeared on HTML5 Doctor on November 15, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/history-api/feed/ 26
Storing Data the Simple HTML5 Way (and a few tricks you might not have known) https://stevefaulkner.github.io/html5doctored/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known/ https://stevefaulkner.github.io/html5doctored/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known/#comments Tue, 23 Aug 2011 14:00:36 +0000 http://html5doctor.com/?p=3600

Related Posts:

]]>
Yes indeed people, it’s your favourite HTML5 Doctor with JavaScript knowledge who lives in Brighton near a golf course! I’m also shooting for the longest title we’ve published so far – and I think I’m in the lead.

This post is about the Web Storage API. Technically it’s been shifted out of the HTML5 specification and can now be found in it’s very own dedicated spec. But if it counts at all – it used to be part of the Web Applications spec.

Web Storage is a very, very simple way to store data in the client – i.e. the browser. What’s more, the support is fabulous: IE8 and upwards has support natively, and there’s lots of good polyfills in the wild already.

This post however will just focus on the features of Web Storage and hopefully show you a trick or two you may not have known about.

What Web Storage Does

Using JavaScript, Web Storage makes it possible to easily store arbitrary values in the browser. Storage is different from cookies in that it’s not shared with the server. It’s also different from cookies in that it’s dead simple to work with.

There are two versions of Web Storage: local and session. Local means that it’s persistent, and session is simply that the data is lost when the session ends (i.e. when you close you browser window or tab). It’s also worth noting that a session is tied to a single browser window or tab. The session doesn’t leak out in to other open windows on that same domain.

Any data stored is tied to the document origin, in that it’s tied to the specific protocol (http or https, etc), the host (html5doctor.com) and the port (usually port 80).

Get Storing

The API for localStorage and sessionStorage is exactly the same, and distills down to the following methods:

  • .setItem(key, value);
  • .getItem(key)
  • .removeItem(key)
  • .clear()
  • .key(index)
  • .length

You can probably guess what most of those methods do, maybe not the last two, but ignore all that syntax for a moment.

Due to the way that the storage API has been defined, the set/get/remove methods all are getters, setters and deleters. What that means to you is you can use localStorage as follows:

localStorage.name = 'Remy';

If you tried using the link above, this will save a property called “name” against localStorage. Completely closing your browser, and going back to http://jsconsole.com and test the name property again:

console.log(localStorage.name);

Still holds the value doesn’t it? Pretty easy eh? And no faffing around with cookies, for that, we can be thankful!

Equally deleting data is very easy:

delete localStorage.name;
console.log(localStorage.name);

You’ll see the value is undefined.

What’s happening under the hood is that when you set a property on localStorage (or sessionStorage) it’s calling the .setItem method. When you get a property, it’s calling .getItem and when you delete, it’s calling removeItem. That way you can treat the Web Storage interface as any other regular object in JavaScript, except you’ll know it’ll hang around after the page has unloaded.

Hey everyone! I’m storing some data!

That’s what your browser does when you store some data. It announces it via events.

When you set some data on localStorage or sessionStorage, an event, called “storage”, fires on all the other windows on the same origin.

To listen for events the following code is used:

function storageEvent(event) {
  event = event || window.event; // give IE8 some love
  alert('Yo people! Something just got stored!');
}

if (window.attachEvent) { // ::sigh:: IE8 support
   window.attachEvent('onstorage', storageEvent);
} else {
    window.addEventListener('storage', storageEvent, false);
}

Note that as IE8 has support, if you don’t want to use onstorage you’ll want to double up your event listeners with attachEvent.

Clearly a massive alert box isn’t useful, but what is useful is what you capture inside of the event object:

  • key – the property name of the value stored
  • newValue – the newly set value (duh!)
  • oldValue – the previous value before being overwritten by .newValue
  • url – the full url path of the origin of the storage event
  • storageArea – the storage object, either localStorage or sessionStorage

With this information, you can do a lot with the storage event, like perhaps keep tabs that are open synchronised. Here’s a simple, contrived example of using localStorage to echo a value across different windows on html5demos.com.

Or for a real world example, Font Deck recently implemented this very feature, if you change the sample text in one window, all other open tabs (or windows) mirror that same sample text.

Gotchas to watch out for

The main gotcha with Web Storage is that although the specification used to say† that any object type can be stored, in fact all browsers currently coerce to strings. That means if you want to store a JavaScript object (or an array perhaps), you’ll need to use JSON to encode and decode:

var doctors = [
  'rem', 
  'rich_clark', 
  'brucel', 
  'jackosborne', 
  'leads', 
  'akamike', 
  'boblet'];
localStorage.doctors = JSON.stringify(doctors);

// later that evening…
var html5docs = JSON.parse(localStorage.doctors);
alert('There be ' + html5docs.length + ' doctors in the house');

† Edited thanks to feedback from zcorpan

When working with storage events, a couple of things to also watch out for – this is on purpose of course, but still just about qualify for gotcha status:

  1. The event only fires on the other windows – it won’t fire on the window that did the storing.
  2. The event won’t fire if the data doesn’t change, i.e. if you store .name = ‘Remy’ and set it to ‘Remy’ again it won’t fire the storage event (obviously, since nothing was stored).

and finally…

If you want to use web storage in browsers like IE6 and IE7 (or rather than want: need to in your particular case) – then there’s no shortage of polyfills for Web Storage. However be wary that you’ll need to stick to the regular setItem syntax rather than being able to use the sexy setter/getter syntax – and I’ve yet to see a polyfill that supports the storage events.

Maybe that isn’t a problem for you though – maybe the sheer simplicity and spiffingness of Web Storage is enough to just support IE8 and above with this enhanced client storage model.

Storing Data the Simple HTML5 Way (and a few tricks you might not have known) originally appeared on HTML5 Doctor on August 23, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/storing-data-the-simple-html5-way-and-a-few-tricks-you-might-not-have-known/feed/ 30
Finding your position with Geolocation https://stevefaulkner.github.io/html5doctored/finding-your-position-with-geolocation/ https://stevefaulkner.github.io/html5doctored/finding-your-position-with-geolocation/#comments Tue, 14 Jun 2011 14:35:07 +0000 http://html5doctor.com/?p=3324 The Geolocation API provides a method to locate the user's exact (more or less - see below) position. This is useful in a number of ways ranging from providing a user with location specific information to providing route navigation.

]]>
The Geolocation API provides a method to locate the user’s exact (more or less – see below) position. This is useful in a number of ways ranging from providing a user with location specific information to providing route navigation.

Although it’s not actually part of the HTML5 specification, as it was developed as a separate specification by the W3C, rather than the WHATWG, if the esteemed HTML5 Doctors Remy Sharp and Bruce Lawson felt it was fitting enough to include in their book, then it’s perfectly ok to write about it here.

The API is actually remarkably simple to use and this article aims to introduce the API and show just how easy it is.

Browser Compatibility

Currently the W3C Geolocation API is supported by the following desktop browsers:

  • Firefox 3.5+
  • Chrome 5.0+
  • Safari 5.0+
  • Opera 10.60+
  • Internet Explorer 9.0+

There is also support for the W3C Geolocation API on mobile devices:

  • Android 2.0+
  • iPhone 3.0+
  • Opera Mobile 10.1+
  • Symbian (S60 3rd & 5th generation)
  • Blackberry OS 6
  • Maemo

Data Protection

The specification explicitly states that since the nature of the API also exposes the user’s location and therefore could compromise their privacy, the user’s permission to attempt to obtain the geolocation information must be sought before proceeding. The browser will take care of this, and a message will either appear as a popup box, or at the top of the browser (implementation is browser specific) requesting the user’s permission.

Screenshot of Safari's popup box asking for Geolocation permission
Safari asking the user for permission to obtain their Geolocation information

Geolocation sources

A number of different sources are used to attempt to obtain the user’s location, and each has their own varying degree of accuracy. A desktop browser is likely to use WiFi (accurate to 20m) or IP Geolocation which is only accurate to the city level and can provide false positives. Mobile devices tend to use triangulation techniques such as GPS (accurate to 10m and only works outside), WiFi and GSM/CDMA cell IDs (accurate to 1000m).

Using the API

Before you actually attempt to use the Geolocation API, you first need to check if the browser actually supports it. The API usefully provides a function for this which can be called as follows:

if (navigator.geolocation) {
  // do fancy stuff
}

Obviously if this returns false, you should optionally inform the user of the inferiority of their browser and laugh in their face (not really).

Through the API, there are two functions available to obtain a user’s location:

getCurrentPosition and watchPosition

Both of these methods return immediately, and then asynchronously attempt to obtain the current location. They take the same number of arguments, two of which are optional:

  1. successCallback – called if the method returns successfully
  2. [errorCallback] – called if the method returns with an error
  3. [options] – a number of options are available:
    • enableHighAccuracy – provides a hint that the application would like the best possible results. This may cause a slower response time and in the case of a mobile device, greater power consumption as it may use GPS. Boolean with a default setting of false.
    • timeout – indicates the maximum length of time to wait for a response. In milliseconds with a default of 0 – infinite.
    • maximumAge – denotes the maximum age of a cached position that the application will be willing to accept. In milliseconds, with a default value of 0, which means that an attempt must be made to obtain a new position object immediately.

Before mentioning the differences between the two, another method needs to be introduced:

clearWatch

This method takes one argument, the watchID of the watch process to clear (which is returned by watchPosition)

Now, the main difference between getCurrentPosition and watchPosition is that watchPosition keeps informing your code should the position change, so basically it keeps updating the user’s position. This is very useful if they’re on the move and you want to keep track of their position, whereas getCurrentPosition is a once off. This method also returns a watchID which is required when you want to stop the position constantly being updated by calling clearWatch method is called.

When the user’s position is returned, it is contained within a Position object which contains a number of properties:

Property Details
coords.latitude Decimal degrees of the latitude
coords.longitude Decimal degress of the longitude
coords.altitude Height in metres of the position above the reference ellipsoid
coords.accuracy The accuracy in metres of the returned result. The value of this setting informs the application how useful the returned latitude/longitude value actually is. This can help in determining if the returned result is accurate enough for the purpose it is intended for, e.g. values for streetview locations will need to be more accurate than those for a country based location
coords.altitudeAccuracy The accuracy in metres of the returned altitude
coords.heading Direction of travel of the hosting device, clockwise from true north
coords.speed The current ground speed of the hosting device in metres per second
timestamp Timestamp of when the position was acquired

Amongst these only which is coords.latitude, coords.longitude and coords.accuracy are guaranteed to be returned (all others may be null), and the first two are by and large the most relevant, as it is from these that a position can be plotted on a Google Map, for example.

You can read more about the Position object and the coordinates interface on the W3 specification itself.

Putting it all together

Putting this altogether, the following code will attempt to obtain a user’s location, calling the method displayPosition on success which simply pops up an alert box with the captured latitude and longitude:

if (navigator.geolocation) {
  var timeoutVal = 10 * 1000 * 1000;
  navigator.geolocation.getCurrentPosition(
    displayPosition, 
    displayError,
    { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
  );
}
else {
  alert("Geolocation is not supported by this browser");
}

function displayPosition(position) {
  alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}

The code above also calls the displayError method when attempt to fetch the user’s location data. This function simple converts the returned error code to an appropriate message:

function displayError(error) {
  var errors = { 
    1: 'Permission denied',
    2: 'Position unavailable',
    3: 'Request timeout'
  };
  alert("Error: " + errors[error.code]);
}

A final word

This is just a simple introduction to using the Geolocation API and one of it’s uses.

Of course the API can be used for more than simply plotting a position on a map (although that in itself is quite useful). The specification itself offers a list of potential use cases for the API such as:

  • Finding and plotting points of interest in the user’s area
  • Annotating content with location informationShowing a user’s position on a map (helping with directions of course!)
  • Turn-by-turn route navigation – using watchPosition
  • Up-to-date local information – updates as you move

Examples

To see geolocation in action, I’ve put together a couple of quick examples in which I encourage you to view source and then go and try it out for yourself.

Finding your position with Geolocation originally appeared on HTML5 Doctor on June 14, 2011.

]]>
https://stevefaulkner.github.io/html5doctored/finding-your-position-with-geolocation/feed/ 43
video + canvas = magic https://stevefaulkner.github.io/html5doctored/video-canvas-magic/ https://stevefaulkner.github.io/html5doctored/video-canvas-magic/#comments Wed, 20 Oct 2010 14:34:53 +0000 http://html5doctor.com/?p=2554 You've already learned about the <video> and <canvas> elements, but did you know that they were designed to be used together? In fact, the two elements are absolutely wondrous when you combine them together. I'm going to show off a few super-simple demos using the two elements together, which should help suggest cool future projects for you fellow web authors.

]]>
You’ve already learned about the <video> and <canvas> elements, but did you know that they were designed to be used together? In fact, the two elements are absolutely wondrous when you combine them! I’m going to show off a few super-simple demos using these two elements, which I hope will prompt cool future projects from you fellow web authors. (All of these demos work in every modern browser except Internet Explorer.)

First, the basics

If you’re just starting with HTML5, you may not be familiar with the <video> element and how to use it. Here’s a simple example that we’ll be using in the later demos:

<video controls loop>
    <source src=video.webm type=video/webm>
    <source src=video.ogg type=video/ogg>
    <source src=video.mp4 type=video/mp4>
</video>

The <video> element contains two attributes: @controls and @loop. @controls tells the browser to give the video the standard set of video controls: play/pause, scrubber, volume, etc. @loop tells the browser to start the video over again from the beginning once it ends.

Then, inside the <video> element, we have three child <source> elements, each pointing to a different encoding of the same video. The browser will try each source in order and play the first one that it understands.

See this code in action, playing the intro to one of the greatest cartoon series of all time.

HTML5 Video playing in Chrome

(A note about fallback: all of these demos assume that your browser has <video> support, which isn’t true in IE8 or earlier. Normally, it’s good practice to specify a Flash fallback or similar for those browsers, but that wouldn’t accomplish much here — all of the techniques I demonstrate rely on basic integration between the <video> element and the <canvas> element, which you can’t achieve with a Flash player. So I’ve omitted any non-<video> fallback content in these examples. I’ve still provided multiple sources, though, so all current browsers that do support <video> will be able to play it.)

Now, a simple example

Now that we know how to play a video, let’s mix in some <canvas> shenanigans. First, check out the demo, then come back here for a code walkthrough. I’ll wait.

…

Drawing video onto the canvas at full screen

Done? Cool! Now, how does this work? Surely it requires a few hundred lines of JavaScript, right? If you’ve cheated and already looked at the source code of the demo page, you’ll know how easy it is.

We start with this HTML:

<!DOCTYPE html>
<title>Video/Canvas Demo 1</title>

<canvas id=c></canvas>
<video id=v controls loop>
    <source src=video.webm type=video/webm>
    <source src=video.ogg type=video/ogg>

    <source src=video.mp4 type=video/mp4>
</video>

Same video code as before, but now with a <canvas> element thrown into the mix. Kinda empty and useless at the moment, though. We’ll script it into action later.

Now, let’s pair that with some CSS to get things positioned right:

<style>

body {
    background: black;
}

#c {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100%;
    height: 100%;
}

#v {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -180px 0 0 -240px;
}
</style>

This just centers the video in the screen and stretches the canvas to the full width and height of the browser window. Since the canvas comes first in the document, it’ll be behind the video, exactly where we want it.

Now, here comes the magic!

<script>
document.addEventListener('DOMContentLoaded', function(){
    var v = document.getElementById('v');
    var canvas = document.getElementById('c');
    var context = canvas.getContext('2d');

    var cw = Math.floor(canvas.clientWidth / 100);
    var ch = Math.floor(canvas.clientHeight / 100);
    canvas.width = cw;
    canvas.height = ch;

    v.addEventListener('play', function(){
        draw(this,context,cw,ch);
    },false);

},false);

function draw(v,c,w,h) {
    if(v.paused || v.ended) return false;
    c.drawImage(v,0,0,w,h);
    setTimeout(draw,20,v,c,w,h);
}
</script>

Take that in for a moment. Just breathe deeply and absorb it. So short, so sweet, so pretty…

Now, let’s step through it.

    var v = document.getElementById('v');
    var canvas = document.getElementById('c');
    var context = canvas.getContext('2d');

    var cw = Math.floor(canvas.clientWidth / 100);
    var ch = Math.floor(canvas.clientHeight / 100);
    canvas.width = cw;
    canvas.height = ch;

This part is simple. I grab hold of the video and canvas elements on the page, and I grab the canvas’s 2D-context so I can draw on it. Then I do some quick calculating to find out how wide and tall I want the canvas’s drawing surface to be. The <canvas> element itself is already stretched to the size of the screen via CSS, so this’ll make each pixel of the drawing surface equal to about 100×100 pixels on the screen.

That last bit may need some explanation if you’re new to canvas. Normally, the visual size and the drawing-surface size of a <canvas> element will be the same. In that case, drawing a line 50px long will display a line 50px long. But that doesn’t have to be true — you can set the drawing surface’s size through the @width and @height properties on the <canvas> element itself, and then change the visual size of the canvas with CSS to be something different. The browser will then automatically upscale or downscale the drawing appropriately to make the drawing surface fill the visual size. In this case, I’m setting the drawing surface of the canvas to be very small — on most screens, it’ll be about 10px wide and 7px tall — and then stretching the visual size with CSS so that each pixel I draw gets blown up 100-fold by the browser. That’s what causes the cool visual effect in the demo.

    v.addEventListener('play', function(){
        draw(v,context,cw,ch);
    },false);

Another simple part. Here I attach some code to the “play” event on the video element. This event gets fired whenever the user hits the “play” button to start watching the video. All I do is call the draw() function with the appropriate parameters: the video itself, the canvas’s drawing context, and the canvas’s width and height.

function draw(v,c,w,h) {
    if(v.paused || v.ended) return false;
    c.drawImage(v,0,0,w,h);
    setTimeout(draw,20,v,c,w,h);
}

The first line just makes the function stop immediately if the user pauses or stops the video, so it’s not burning CPU when nothing’s changing. The third line calls the draw() function again, allowing the browser a little breathing space to do other things like update the video itself. I’m putting in a 20ms delay, so we’ll get roughly 50fps, which is more than enough.

The second line is where the magic happens — it draws the current frame of the video directly onto the canvas. Yes, it’s exactly as simple as it looks. Just pass the video element and the x, y, width, and height of the rectangle on the canvas you want it to draw into. In this case, it’s filling up the entire canvas, but you could do less (or more!) if you wanted.

I’m using another trick here. Remember how the canvas is really tiny? The video will be at least 20 times bigger than the canvas on most screens, so how do we draw it onto such a tiny canvas? The drawImage() function handles that for us — it automatically scales whatever you hand it in the first argument so that it fills the rectangle you specify. That means we authors don’t have to worry about averaging the pixel colors (or extrapolating, if you’re drawing a small video into a big rectangle) because the browser does it all for us. I’ll use this trick more in the future, so watch out for it.

And…that’s it! The entire demo is done in 20 lines of easy-to-read JavaScript code, instantly producing a nifty background effect for any video you wish to play. You can trivially adjust the size of the “pixels” on the canvas by adjusting the lines that set the cw and ch variables.

Directly manipulating video pixels

The last demo was cool, but it just let the browser do all the heavy lifting. The browser downscaled the video, drew it onto the canvas, and then upscaled the canvas pixels, all automatically. Let’s try our hand at doing some of this ourselves! Check out the demo to see this in action, where I convert the video to grayscale on the fly.

Video made greyscale with canvas manipulation

The HTML for the page is basically identical:

<video id=v controls loop>
    <source src=video.webm type=video/webm>
    <source src=video.ogg type=video/ogg>
    <source src=video.mp4 type=video/mp4>
</video>
<canvas id=c></canvas>

Nothing new here, so let’s move onto the script.

document.addEventListener('DOMContentLoaded', function(){
    var v = document.getElementById('v');
    var canvas = document.getElementById('c');
    var context = canvas.getContext('2d');
    var back = document.createElement('canvas');
    var backcontext = back.getContext('2d');

    var cw,ch;

    v.addEventListener('play', function(){
        cw = v.clientWidth;
        ch = v.clientHeight;
        canvas.width = cw;
        canvas.height = ch;
        back.width = cw;
        back.height = ch;
        draw(v,context,backcontext,cw,ch);
    },false);

},false);

function draw(v,c,bc,w,h) {
    if(v.paused || v.ended) return false;
    // First, draw it into the backing canvas
    bc.drawImage(v,0,0,w,h);
    // Grab the pixel data from the backing canvas
    var idata = bc.getImageData(0,0,w,h);
    var data = idata.data;
    // Loop through the pixels, turning them grayscale
    for(var i = 0; i < data.length; i+=4) {
        var r = data[i];
        var g = data[i+1];
        var b = data[i+2];
        var brightness = (3*r+4*g+b)>>>3;
        data[i] = brightness;
        data[i+1] = brightness;
        data[i+2] = brightness;
    }
    idata.data = data;
    // Draw the pixels onto the visible canvas
    c.putImageData(idata,0,0);
    // Start over!
    setTimeout(function(){ draw(v,c,bc,w,h); }, 0);
}

The script is a bit longer this time, because we’re actually doing some work. But it’s still really simple!

document.addEventListener('DOMContentLoaded', function(){
    var v = document.getElementById('v');
    var canvas = document.getElementById('c');
    var context = canvas.getContext('2d');
    var back = document.createElement('canvas');
    var backcontext = back.getContext('2d');

    var cw,ch;

    v.addEventListener('play', function(){
        cw = v.clientWidth;
        ch = v.clientHeight;
        canvas.width = cw;
        canvas.height = ch;
        back.width = cw;
        back.height = ch;
        draw(v,context,backcontext,cw,ch);
    },false);

This is almost the same as I had before, with two real differences.

First, I’m creating a second canvas and pulling the context out of it as well. This is a “backing canvas”, which I’ll use to perform intermediate operations before painting the final result into the visible canvas in the markup. The backing canvas doesn’t even need to be added to the document. It can just hang out here in my script. This strategy will be used a lot in later examples, and it’s quite useful in general, so take note of it.

Second, I’m waiting to resize the canvases until the video is played, rather than just sizing them immediately. This is because the <video> element probably hasn’t loaded its video up when the DOMContentLoaded event fires, so it’s still using the default size for the element. By the time it’s ready to play, though, it knows the size of the video and has sized itself appropriately. At that point, we can set up the canvases to be the same size as the video.

function draw(v,c,bc,w,h) {
    if(v.paused || v.ended) return false;
    bc.drawImage(v,0,0,w,h);

Same as the first demo, the draw() function begins by checking if it should stop, then just draws the video onto a canvas. Note that I’m drawing it onto the backing canvas, which, again, is just sitting in my script and isn’t displayed in the document. The visible canvas is reserved for the displaying the grayscale version, so I use the backing canvas to load up the initial video data.

    var idata = bc.getImageData(0,0,w,h);
    var data = idata.data;

Here’s the first new bit. You can draw something onto a canvas with either the normal canvas drawing functions or drawImage(), or you can just manipulate the pixels directly through the ImageData object. getImageData() returns the pixels from a rectangle of the canvas. In this case, I’m just getting the whole thing.

Warning! If you’re following along and trying to run these demos on your desktop, this is where you’ll probably run into trouble. The <canvas> element keeps track of where the data inside of it comes from, and if it knows that you got something from another website (for example, if the <video> element you painted into the canvas is pointing to a cross-origin file), it’ll “taint” the canvas. You’re not allowed to grab the pixel data from a tainted canvas. Unfortunately, file: urls count as “cross-origin” for this purpose, so you can’t run this on your desktop. Either fire up a web server on your computer and view the page from localhost, or upload it to some other server you control.

    for(var i = 0; i < data.length; i+=4) {
        var r = data[i];
        var g = data[i+1];
        var b = data[i+2];

Now, a quick note about the ImageData object. It returns the pixels in a special way in order to make them easy to manipulate. If you have, say, a 100×100 pixel canvas, it contains a total of 10,000 pixels. The ImageData array for it will then have 40,000 elements, because the pixels are broken up by component and listed sequentially. Each group of four elements in the ImageData array represent the red, green, blue, and alpha channels for that pixel. To loop through the pixels, just increment your counter by 4 every time, like I do here. Each channel, then, is an integer between 0 and 255.

        var brightness = (3*r+4*g+b)>>>3;
        data[i] = brightness;
        data[i+1] = brightness;
        data[i+2] = brightness;

Here, a quick bit of math converts the RGB value of the pixel into a single “brightness” value. As it turns out, our eyes respond most strongly to green light, slightly less so to red, and much less so to blue. So, I weight the channels appropriately before taking the average. Then, we just feed that single value back to all three channels. As we probably all know, when the red, green, and blue values of a color are equal, you get gray. (During this whole process, I’m completely ignoring the fourth member of each group, the alpha channel, because it’s always going to be 255.)

    idata.data = data;

Shove the modified pixel array back into the ImageData object…

    c.putImageData(idata,0,0);

…and then shove the whole thing into the visible canvas! We didn’t need to do any complicated drawing at all! Just grab the pixels, manipulate them, and shove them back in. So easy!

A final note: real-time full-video pixel manipulation is one of those rare places where micro-optimizations actually matter. You can see their effects in my code here. Originally, I didn’t pull the pixel data out of the ImageData object, and just wrote “var r = idata.data[i];” and so on each time, which meant several extra property lookups in every iteration of the loop. I also originally just divided the brightness by 8 and floored the value, which is slightly slower than bit-shifting by 3 places. In normal code, these sorts of things are completely insignificant, but when you’re doing them several million times per second (the video is 480×360, and thus contains nearly 200,000 pixels, each of which is individually handled roughly 100 times a second), those tiny delays add up into a noticeable lag.

More advanced pixel manipulation

You can operate on more than just a single pixel at a time, too, composing some fairly complex visual effects. As I noted at the end of the previous section, performance matters a lot here, but you’d be surprised what you can squeeze out with a little creativity. As you can see in the demo, I’ll be creating an emboss effect in this example, which requires you to use several input pixels together to compute the value of each output pixel.

Embossed video with canvas manipulation

Here’s the code. The HTML and most of the beginning code is identical to the previous example, so I’ve omitted everything but the draw() function:

function draw(v,c,bc,cw,ch) {
    if(v.paused || v.ended) return false;
    // First, draw it into the backing canvas
    bc.drawImage(v,0,0,cw,ch);
    // Grab the pixel data from the backing canvas
    var idata = bc.getImageData(0,0,cw,ch);
    var data = idata.data;
    var w = idata.width;
    var limit = data.length
    // Loop through the subpixels, convoluting each using an edge-detection matrix.
    for(var i = 0; i < limit; i++) {
        if( i%4 == 3 ) continue;
        data[i] = 127 + 2*data[i] - data[i + 4] - data[i + w*4];
    }
    // Draw the pixels onto the visible canvas
    c.putImageData(idata,0,0);
    // Start over!
    setTimeout(draw,20,v,c,bc,cw,ch);
}

Now let’s step through that.

function draw(v,c,bc,cw,ch) {
    if(v.paused || v.ended) return false;
    // First, draw it into the backing canvas
    bc.drawImage(v,0,0,cw,ch);
    // Grab the pixel data from the backing canvas
    var idata = bc.getImageData(0,0,cw,ch);
    var data = idata.data;

Same as the last example. Check to see if we should stop, then draw the video onto the backing canvas and grab the pixel data from it.

var w = idata.width;

The significance of this line needs some explanation. I’m already passing the canvas’s width into the function (as the cw variable), so why am I re-measuring its width here? Well, I was actually lying to you earlier when I explained how large the pixel array will be. The browser might have one pixel of canvas map to one pixel of ImageData, but browsers are allowed to use higher resolutions in the image data, representing each pixel of canvas as a 2×2 block of ImageData pixels, or maybe 3×3, or maybe even greater!

If they use a “high-resolution backing store”, as this is called, it means better display, as aliasing artifacts (jagged edges on diagonal lines) become much smaller and less noticeable. It also means that rather than a 100×100 pixel canvas giving you an ImageData.data object with 40,000 numbers, it might have 160,000 numbers instead. By asking the ImageData for its width and height, we ensure that we loop through the pixel data properly no matter whether the browser uses a low-res or high-res backing store for it.

It’s very important that you use this properly whenever you need the width or height of the data you pulled out as an ImageData object. If too many people screw it up and just use the canvas’s width and height instead, then browsers will be forced to always use a low-res backing store to be compatible with those broken scripts!

    var limit = data.length;
    for(var i = 0; i < limit; i++) {
        if( i%4 == 3 ) continue;
        data[i] = 127 + 2*data[i] - data[i + 4] - data[i + w*4];
    }

I’m grabbing the data’s length and stuffing it into a variable, so I don’t have to pay for a property access on every single iteration of the loop. (Remember, micro-optimizations matter when you’re doing real-time video manipulation!) Then I just loop through the pixels, like I did before. If the pixel happens to be for the alpha channel (every fourth number in the array), I can just skip it — I don’t want to change the transparency. Otherwise, I’ll do a little math to find the difference between the current pixel’s color channel and the similar channels of the pixels below and to the right, then just combine that difference with the “average” gray value of 127. This has the effect of making areas where the pixels are the same color a flat medium gray, but edges where the color suddenly changes will turn either bright or dark.

There’s another optimization here. Because I’m only comparing the current pixel with pixels “further ahead” in the data which I haven’t looked at yet, I can just store the changed value right back in the original data, because nothing will ever look at the current pixel’s data again after this point. This means I don’t have to allocate a big array to hold the results before turning it back into an ImageData object.

    c.putImageData(idata,0,0);
    setTimeout(draw,20,v,c,bc,cw,ch);

Finally, draw the modified ImageData object into the visible canvas, and set up another call to the function in 20 milliseconds. This is the same as the previous example.

Wrapping up

So, we’ve explored the basics of combining HTML5′s <canvas> and <video> elements today. The demos were very basic, but they illustrated all the essential techniques you’ll need to do something even cooler on your own:

  1. You can draw a video directly onto a canvas.
  2. When you draw onto a canvas, the browser will automatically scale the image for you if necessary.
  3. When you display a canvas, the browser will again scale it automatically if the visible size is different from the size of the backing-store.
  4. You can do direct pixel-level manipulation of a canvas by just grabbing the ImageData, changing it, and drawing it back in.

In Part 2 of this article [Ed: coming soon!], I’ll explore some more interesting applications of video/canvas integration, including a real-time video-to-ASCII converter!

video + canvas = magic originally appeared on HTML5 Doctor on October 20, 2010.

]]>
https://stevefaulkner.github.io/html5doctored/video-canvas-magic/feed/ 81
Introducing Web SQL Databases https://stevefaulkner.github.io/html5doctored/introducing-web-sql-databases/ https://stevefaulkner.github.io/html5doctored/introducing-web-sql-databases/#comments Wed, 24 Feb 2010 10:15:39 +0000 http://html5doctor.com/?p=1408

Related Posts:

]]>
The Web SQL database API isn’t actually part of the HTML5 specification, but it is part of the suite of specifications that allows us developers to build fully fledged web applications, so it’s about time we dig in and check it out.

What’s in the box?

If you haven’t guessed from the overly verbose specification title, Web SQL Databases is a spec that brings SQL to the client side. If you have a back-end developer’s background, then you’ll probably be familiar with SQL and happy as a pig in muck. If not, you might want to learn some SQL before you start hacking around, Google’s your friend here.

The specification is based around SQLite (3.1.19), but having come from MySQL myself, it’s all pretty much the same (sorry for the sweeping statement!).

For an example of Web SQL Databases working, have a look at the Twitter HTML5 chatter demo I put together. It uses SQL and the WHERE clause to narrow down the recent chat about HTML5 on Twitter (it will work in Safari, Chrome and Opera 10.50).

There are three core methods in the spec that I’m going to cover in this article:

  1. openDatabase
  2. transaction
  3. executeSql

Support is a little patchy at the moment. Only Webkit (Safari, SafariMobile and Chrome) and Opera 10.50 (ATOW alpha on Mac) support web databases. Fellow Doctor Bruce Lawson has told me that Firefox are holding off as they feel there’s a better implementation than SQLite (though I hope it’s similar, whatever they pick). Either way, I’d definitely recommend checking out the SQLite documentation for the functions that are available.

Because of this patchy support and the simple fact that Webkit had implemented the database spec some time ago, the spec on the W3C is now slightly ahead of the implementations in Safari, while Webkit is still catching up. On the other hand, since Opera has only just added support, it’s closer to the spec (I’ll mention the differences as we go along).

Nonetheless, it’s fun to play with, so let’s get playing!

Creating and Opening Databases

If you try to open a database that doesn’t exist, the API will create it on the fly for you. You also don’t have to worry about closing databases.

To create and open a database, use the following code:

var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);

I’ve passed four arguments to the openDatabase method. These are:

  1. Database name
  2. Version number
  3. Text description
  4. Estimated size of database

The missing feature of openDatabase (I’m not sure when it was added) is the fifth argument:

  1. Creation callback

The creation callback will be called if the database is being created. Without this feature, however, the databases are still being created on the fly and correctly versioned.

The return value from openDatabase contains the transaction methods, so we’ll need to capture this to be able to perform SQL queries.

Estimated database size

From the tests I’ve run, only Safari prompts the user if you try to create a database over the size of the default database size, 5MB. The prompt is shown the image below, asking whether you want to grant the database permission to scale up to the next size of database — 5, 10, 50, 100 and 500MB. Opera, on the other hand, builds the database without complaining, which I expect might change later as it’s still in alpha.

Webkit database size prompt

Versions

I could be wrong, but everything I’ve tested so far says that versioning in SQL databases is borked. The problem is this:

If you upgrade your database to version 2.0 (e.g., there are some important schema changes since version 1.0), how do you know which visitors are on version 1.0 and which are on version 2.0?

The version number is a required argument to openDatabase, so you must know the version number before you try to open it. Otherwise, an exception is thrown.

Also, changeVersion, the method to change the database version, is not fully supported in Webkit. It works in Chrome and Opera, but not in Safari or Webkit. Regardless, if I can’t determine which version of database the user is on, then I can’t upgrade the user.

A possible workaround is to maintain a state database, something like the ‘mysql’ database in MySQL. This way, you would only have one version of this state database, and within this you would record the current version of any databases that control your application. It’s a hack, but it works.

Transactions

Now that we’ve opened our database, we can create transactions. Why bother with transactions instead of just running our SQL? Transactions give us the ability to rollback. This means that if a transaction — which could contain one or more SQL statements — fails (either the SQL or the code in the transaction), the updates to the database are never committed — i.e. it’s as if the transaction never happened.

There are also error and success callbacks on the transaction, so you can manage errors, but it’s important to understand that transactions have the ability to rollback changes.

The transaction is simply a function that contains some code:

var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);
db.transaction(function (tx) {
  // here be the transaction
  // do SQL magic here using the tx object
});

I recently uploaded a demo to html5demos.com that demonstrates a transaction rollback in action: Web SQL database rollback demo

In the nightly builds of the browsers, we also have db.readTransaction, which allows only read statements to run on the database. I assume there are performance benefits to using a read-only readTransaction instead of a read/write transaction, most probably to do with table locking.

Now that we’ve got our transaction object (named tx in my example) we’re ready to run some SQL!

executeSql

This is the funnel of love for all your SQL goodness. executeSql is used for both read and write statements, includes SQL injection projection, and provides a callback method to process the results of any queries you may have written.

Once we have a transaction object, we can call executeSql:

var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);
db.transaction(function (tx) {
  tx.executeSql('CREATE TABLE foo (id unique, text)');
});

This will now create a simple table called “foo” in our database called “mydb”. Note that if the database already exists the transaction will fail, so any successive SQL wouldn’t run. So we can either use another transaction, or we can only create the table if it doesn’t exist, which I’ll do now so I can insert a new row in the same transaction:

var db = openDatabase('mydb', '1.0', 'my first database', 2 * 1024 * 1024);
db.transaction(function (tx) {
  tx.executeSql('CREATE TABLE IF NOT EXISTS foo (id unique, text)');
  tx.executeSql('INSERT INTO foo (id, text) VALUES (1, "synergies")');
});

Now our table has a single row inside it. What if we want to capture the text from the user or some external source? We’d want to ensure it can’t compromise the security of our database (using something nasty like SQL injection). The second argument to executeSql maps field data to the query, like so:

tx.executeSql('INSERT INTO foo (id, text) VALUES (?, ?)', [id, userValue]);

id and userValue are external variables, and executeSql maps each item in the array argument to the “?”s.

Finally, if we want to select values from the table, we use a callback to capture the results:

tx.executeSql('SELECT * FROM foo', [], function (tx, results) {
  var len = results.rows.length, i;
  for (i = 0; i < len; i++) {
    alert(results.rows.item(i).text);
  }
});

(Notice that in this query, there are no fields being mapped, but in order to use the third argument, I need to pass in an empty array for the second argument.)

The callback receives the transaction object (again) and the results object. The results object contains a rows object, which is array-like but isn’t an array. It has a length, but to get to the individual rows, you need to use results.rows.item(i), where i is the index of the row. This will return an object representation of the row. For example, if your database has a name and an age field, the row will contain a name and an age property. The value of the age field could be accessed using results.rows.item(i).age.

That’s all you should need to get started with Web SQL Databases. I’m certain that mini JavaScript libraries are going to emerge to help support working with databases. If you want to find out more about SQL databases (shameless self promotion begins) I just finished the storage chapter for Introducing HTML5, which I’m writing with fellow Doc Bruce, so check that bad boy out too!

Demos

Introducing Web SQL Databases originally appeared on HTML5 Doctor on February 24, 2010.

]]>
https://stevefaulkner.github.io/html5doctored/introducing-web-sql-databases/feed/ 94