Nasty Canvas Image Data Error

Last night I decided to revisit an experiment I wrote earlier in the year: Using Image Data Inside the HTML5 Canvas Element. It involved loading 2 – 3 images and swapping out the image data depending on the mouse position. I ran into a slight issue though, it wasn’t working:

uncaught exception: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMCanvasRenderingContext2D.drawImage]"  nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame :: /lab/experiments/canvas-image-data/js/ci.js :: anonymous :: line 27"  data: no]

Not good! I double checked the code on my local machine and it worked. Very odd! I noticed that it wasn’t working when you first hit the page but was on page reload. Then it struck me; it must be a caching issue. I was correct.

It turns out that the JavaScript was firing before all the images had fully loaded.

context.drawImage(lakeImage, 0, 0);
var originalLakeImageData = context.getImageData(0,0, iWidth, iHeight);

The above lines were trying to access ImageData that didn’t exist yet and the browser was falling over because of it. Doh! Luckily I’d used jQuery for a couple of functions in the experiment so I quickly wrapped the code in a load method, problem solved!

    //Your code here

This method waits until the whole page has loaded (including images) before the code inside it is fired, guaranteeing the image data is there to be manipulated when needed. View the updated demo.