2

I want to implement ctrl+c event in canvas (like in painters) from selected region to OS buffer. Based on this answer I can add copy listener and change clipboard data there - which works perfectly with text. But I can't find how to put Image/ImageData object there there. Here's MDN copy documentation and setData. Seems like there is nothing about image/* format. Well Specification doesn't say anything as well. But I smell if first param named as format in setData there should be a way to put file there.

Here's where I come so far:

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(); 
})

I also found setDragImage method, I implemented it but after putting Image it doesn't appear in buffer.

NOTE:

When I paste image FROM clipboard my 'paste' event shows event structure like on the image bellow, so I guess I need create something similar.enter image description here

Any Ideas?

p.s. I also know about document.execCommand('copy');, but it doesn't work in chrome (at least in my case) so I don't wanna use it.

deathangel908
  • 8,601
  • 8
  • 47
  • 81

1 Answers1

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.

ZachB
  • 13,051
  • 4
  • 61
  • 89