如果能够在Stack Exchange上将图像粘贴到此处而不是干预文件对话框,那将非常方便。此处已实现了类似功能,但仅适用于Webkit浏览器。
我正在开发可以做到这一点的用户脚本。有趣的是,在Webkit浏览器中,我从未从剪贴板中获取文件(与原始图像数据不同),而在Firefox中却可以。
Firefox解决方案:
div.addEventListener('paste', function(event){
//I'm actually not sure what should event.originalEvent be. I copypasted this
var items = (event.clipboardData || event.originalEvent.clipboardData);
console.log("paste", items);
//Try to get a file and handle it as Blob/File
var files = items.items || items.files;
if(files.length>0) {
//Being lazy I just pick first file
var file = files[0];
//handle the File object
_this.processFile(file);
event.preventDefault();
event.cancelBubble = true;
return false;
}
});
Run Code Online (Sandbox Code Playgroud)
在Chrome没有像Firefox一样好的文档(我的意思是MDN)之前,我试图检查正在发生的事情。我复制了一个文件,并将其粘贴到Google chrome(v39)中。这是我DataTransfer在控制台中获得的对象:

供参考,这是Firefox中的同一事件:

另外两个阵列,items …
当用户复制画布选择时,我正在尝试将图像放入剪贴板:

所以我认为正确的方法是将canvas tu dataURL,dataURL转换为blob和blob转换为二进制字符串.
理论上应该可以跳过blob,但我不知道为什么.
所以这就是我做的:
function copy(event) {
console.log("copy");
console.log(event);
//Get DataTransfer object
var items = (event.clipboardData || event.originalEvent.clipboardData);
//Canvas to blob
var blob = Blob.fromDataURL(_this.editor.selection.getSelectedImage().toDataURL("image/png"));
//File reader to convert blob to binary string
var reader = new FileReader();
//File reader is for some reason asynchronous
reader.onloadend = function () {
items.setData(reader.result, "image/png");
}
//This starts the conversion
reader.readAsBinaryString(blob);
//Prevent default copy operation
event.preventDefault();
event.cancelBubble = true;
return false;
}
div.addEventListener('copy', copy);
Run Code Online (Sandbox Code Playgroud)
但是当DataTransfer对象在paste事件线程之外使用时,setData不再有任何机会生效. …