JKirchartz JKirchartz - 8 months ago 51
Javascript Question

HTML5/Canvas onDrop event isn't firing?

I'm playing with file upload, drag and drop, and canvas, but for some reason the ondrop function never seems to run, here's the fiddle I'm working in: http://jsfiddle.net/JKirchartz/E4yRv/

the relevant code is :

canvas.ondrop = function(e) {
var file = e.dataTransfer.files[0],
reader = new FileReader();
reader.onload = function(event) {
var img = new Image(),
imgStr = event.target.result;
state.innerHTML += ' Image Uploaded: <a href="' +
imgStr + '" target="_blank">view image</a><br />';
img.src = event.target.result;
img.onload = function(event) {
context.height = canvas.height = this.height;
context.width = canvas.width = this.width;
context.drawImage(this, 0, 0);
state.innerHTML += ' Canvas Loaded: <a href="' + canvas.toDataURL() + '" target="_blank">view canvas</a><br />';
return false;

why doesn't this event fire? I've tried it in firefox and chrome.


In order to get the drop event to fire at all you need to have an ondragover function:

canvas.ondragover = function(e) {
    return false;

If you try to drag your cat picture into the canvas it'll still not work, this error is reported in the Firefox console:

[04:16:42.298] uncaught exception: [Exception... "Component returned failure code: 0x80004003 (NS_ERROR_INVALID_POINTER) [nsIDOMFileReader.readAsDataURL]"  nsresult: "0x80004003 (NS_ERROR_INVALID_POINTER)"  location: "JS frame :: http://fiddle.jshell.net/_display/ :: <TOP_LEVEL> :: line 57"  data: no]

However it will work if you drag an image from your desktop. I think for images in the page you should use regular DOM access methods, the File API is only needed for external files dragged into the browser.