HTML5/Canvas onDrop event isn't firing?

2019-05-12 18:40发布

问题:

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) {
        e.preventDefault();
        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 />';
            };
        };
        reader.readAsDataURL(file);
        return false;
    };

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

回答1:

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

canvas.ondragover = function(e) {
    e.preventDefault();
    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.



回答2:

As far as I can tell, robertc's answer is how browsers continue to behave, you have to have an ondragover function set.

But to expand on it slightly, the function must return false and not true or undefined-- no-op functions will return undefined. It doesn't seem to matter whether you prevent default, the ondrop event handler will trigger. You will want a preventDefault in the ondrop function, otherwise the file will be immediately downloaded to your browser's default download folder:

document.getElementById('drop-zone').ondragover = function(e) {
  return false;
}

document.getElementById('drop-zone').ondrop = function(e) {
  e.preventDefault();
  console.log('ondrop', e);
}
#drop-zone {
  border: solid;
  height: 3em;
  width: 10em;
}
<div id="drop-zone">Drop zone</div>