HTML5 / Canvas onDrop事件没有被触发? [英] HTML5/Canvas onDrop event isn't firing?
问题描述
我正在玩文件上传,拖放和画布,但由于某些原因,ondrop函数似乎永远不会运行,这是我正在努力的小提琴: http://jsfiddle.net/JKirchartz/E4yRv/
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/
相关代码是:
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;
};
为什么这个事件不会发生?我已经在firefox和chrome中尝试过了。
why doesn't this event fire? I've tried it in firefox and chrome.
推荐答案
为了让drop事件全部发生你需要拥有 ondragover
函数:
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;
};
如果你试图将你的猫图片拖到画布上它仍然无效,这个错误是在Firefox控制台中报告:
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]
但是如果你从桌面拖动图像。我认为对于页面中的图像,您应该使用常规DOM访问方法,只有将外部文件拖入浏览器才需要File API。
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.
这篇关于HTML5 / Canvas onDrop事件没有被触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!