HTML Canvas, drawImage and onload

I recently had a play with the HTML <canvas> element as an alternative to creating a simple animated UI in Flex or Flash. When it came to using the drawImage function I hit upon a strange problem.

The drawImage method of the canvas context is used to write image data onto the canvas from an HTMLImageElement, from another canvas or from an HTML <video> element. I was attempting to draw the contents of an <img> tag into the canvas but almost every page load was getting the following error from Firefox:

uncaught exception: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIDOMCanvasRenderingContext2D.drawImage]“  nsresult: “0×80040111 (NS_ERROR_NOT_AVAILABLE)”  location: “JS frame :: http://localhost/canvas/js/interface.js :: anonymous :: line 114″  data: no]

After much confusion I realised that I was setting up the canvas in a DOM ready event handler so it made sense that if the image hadn’t also loaded, its data wouldn’t be available to be drawn. Switching to the onload event cured the issues.

Tags: , , , , ,

Leave a Comment