2

我想在画布(如画家)中从选定区域到操作系统缓冲区实现ctrl+c事件。基于这个答案,我可以在copy那里添加侦听器并更改剪贴板数据 - 这与文本完美配合。但我找不到如何在那里放置Image/对象。ImageData这是 MDN复制文档和setData。似乎没有什么关于image/*格式的。那么规范也没有说什么。但是我闻到如果第一个参数命名为formatinsetData应该有一种将文件放在那里的方法。

这是我到目前为止的地方:

document.addEventListener('copy', function(e) {
   var data = ctx.getImageData(params.left, params.top, params.width, params.height);
   var file = new File(data.data, "file.png", {type: "image/png"});
   e.clipboardData.items.add(file, 'image/png'); // This doesn't work, But it create the structure like on the image below(with items and types, but without FileList) 
   e.clipboardData.setDragImage(tool.img, 10, 10); // doesn't work 
   e.clipboardData.setData("image/png", tool.file); // doesn't work
   e.preventDefault(); 
})

我还找到了 setDragImage方法,我实现了它,但是在将Image它放入缓冲区之后它并没有出现。

笔记:

当我剪贴板粘贴图像时,我的“粘贴”事件显示如下图所示的事件结构,所以我想我需要创建类似的东西。在此处输入图像描述

有任何想法吗?

ps 我也知道document.execCommand('copy'); ,但它在 chrome 中不起作用(至少在我的情况下),所以我不想使用它。

4

1 回答 1

2

Speaking only from my observations and investigation:

  • Chrome does not support the "image/png" type, and this is not a format that is required by the Clipboard API spec. (Chrome bug.)

  • Firefox will at least attempt to put a DataTransferItem with the "image/png" type on the clipboard, but I haven't yet figured out what data format to use. (A base64 PNG, with or without the data:image/png;base64, prefix, does not work to paste into PowerPoint, nor does atob(<the base64 PNG without prefix>), as far as I've experimented.)

  • "text/html" is required however. When a copy event is triggered in Google Docs, it appears to upload an image, then puts an HTML fragment on the clipboard that looks like this:

    <meta charset="utf-8">
    <b style="font-weight:normal;" id="docs-internal-guid-abcdefg-abcd-abcd">
      <img src="https://lh4.googleusercontent.com/a-very-long-identifier" width="659px;" height="312px;" />
    </b>
    

    using evt.clipboardData.setData("text/html", fragment). Then, e.g. Microsoft Office apps will download that image and embed it in the document. I don't know if it does the same thing on MacOS or Linux. Data URIs do not work as the img src, by the way.

于 2017-07-25T18:25:43.603 回答