0

I'm trying to copy the image of a canvas to my clipboard in a lightning component using javascript. So far I have this in my helper:

copyData: function() {
    this.canvas = component.find("canvas").getElement();
    var hiddenInput = document.createElement("input");
    hiddenInput.setAttribute("value", this.canvas.toDataURL());
    document.body.appendChild(hiddenInput);

    hiddenInput.select();
    document.execCommand("copy");

    document.body.removeChild(hiddenInput);
},

This works, but when I paste, it pastes out the base64 string. Is there any way I can tweak this so it pastes the full image (from the data url) instead?

0

If you check your code, you'll notice that you are using HTMLCanvasElement's .toDataURL() method, which, according to Mozilla's documentation:

HTMLCanvasElement.toDataURL()

Returns a data-URL containing a representation of the image in the format specified by the type parameter (defaults to png). The returned image is in a resolution of 96dpi.

To get a Blob of the data, which is an object that represents a file-like object of immutable, raw data, you should use .toBlob() instead:

HTMLCanvasElement.toBlob()

Creates a Blob object representing the image contained in the canvas; this file may be cached on the disk or stored in memory at the discretion of the user agent.

Note that .toBlob() does not work on Microsoft Edge.

But how to render a Blob on a canvas?

See this question on StackOverflow.


Edit

It looks like Chrome (and other major browsers) do not support copying and pasting blobs from the clipboard. The solution, in my opinion, would be to use Base64.

W3C Clipboard specs say that there are generic "read" and "write" methods to the clipboard. But Mozilla's documentation on this API state that they don't support those yet. They only support text for now. A blog post by Google also confirms this.

2
  • How would I get that blob onto the clipboard? I tried swapping out for the blob, and '[object Blob]' is being copied now – Will May 25 '19 at 17:45
  • Uh, okay... I did some research, and it looks like Chrome (or any other browser) doesn't support copying and pasting Blobs yet, just text. You can see in the Clipboard API spec (w3c.github.io/clipboard-apis) that there are "read" and "write" methods. Chrome currently implements only "readText" and "writeText". So it looks like you will have to use Base64 to copy and paste the image for now. I'll add some more links to the question. – Renato Oliveira May 26 '19 at 13:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.