HTML5/Canvas onDrop事件未触发?

JKi*_*rtz 3 javascript html5 html5-canvas

我正在玩文件上传,拖放和画布,但由于某种原因,ondrop函数似乎永远不会运行,这里是我工作的小提琴:http://jsfiddle.net/JKirchartz/E4yRv/

相关代码是:

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;
    };
Run Code Online (Sandbox Code Playgroud)

为什么这个事件没有发生?我在firefox和chrome中尝试过它.

rob*_*rtc 11

为了让drop事件发生,你需要有一个ondragover函数:

canvas.ondragover = function(e) {
    e.preventDefault();
    return false;
};
Run Code Online (Sandbox Code Playgroud)

如果您尝试将猫图片拖动到画布中它仍然无效,则会在Firefox控制台中报告此错误:

[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]
Run Code Online (Sandbox Code Playgroud)

但是,如果从桌面拖动图像,它将起作用.我认为对于页面中的图像,您应该使用常规的DOM访问方法,只有将外部文件拖入浏览器才需要File API.