Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to copy a canvas image to the clipboard?

I've created an image from my canvas object by using canvas.toDataURL("image/png", 0.7). It works fine to save the image from the context menu but it doesn't work to copy the image to the clipboard and paste it into a mail or a word document for example. Is it possible to get "copy to clipboard" to behave the same way it does for a "normal" image?

I'm thinking of creating a small server component that can take the base64 representation of the image and return a "normal" png image that I will be able to copy to clipboard. Could this work as a workaround?

Edit: To clearify: I'm using canvas.toDataURL("image/png", 0.7) to create an image from the canvas and I then set the src attribute of an img tag to the result. I can then select "copy image" from the context menu when right clicking on the image. The problem is then that I can't paste the image into Word and emails (Outlook at least). Pasting into Wordpad and mspaint works fine.

like image 393
gusjap Avatar asked Jan 09 '15 15:01

gusjap


2 Answers

Clipboard API for images are now available on chrome

https://github.com/web-platform-tests/wpt/tree/master/clipboard-apis

const item = new ClipboardItem({ "image/png": blob });
navigator.clipboard.write([item]); 

Example

const canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#eee";
ctx.fillRect(10, 10, 50, 50);

//tested on chrome 76
canvas.toBlob(function(blob) { 
    const item = new ClipboardItem({ "image/png": blob });
    navigator.clipboard.write([item]); 
});
like image 74
Adriano Tumminelli Avatar answered Oct 04 '22 06:10

Adriano Tumminelli


You can convert the canvas to img, put in inside a <div contenteditable>, select it and copy it.

var img = document.createElement('img');
img.src = canvas.toDataURL()

var div = document.createElement('div');
div.contentEditable = true;
div.appendChild(img);
document.body.appendChild(div);

// do copy
SelectText(div);
document.execCommand('Copy');
document.body.removeChild(div);

The SelectText function is from https://stackoverflow.com/a/40547470/1118626

function SelectText(element) {
    var doc = document;
    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(element);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}
like image 21
df1 Avatar answered Oct 04 '22 04:10

df1