javascript 是否可以将画布图像复制到剪贴板?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27863617/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:06:00  来源:igfitidea点击:

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

javascripthtmlimagecanvas

提问by gusper

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?

我已经使用canvas.toDataURL("image/png", 0.7). 从上下文菜单中保存图像可以正常工作,但无法将图像复制到剪贴板并将其粘贴到例如邮件或 Word 文档中。是否可以将“复制到剪贴板”的行为与“正常”图像的行为相同?

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?

我正在考虑创建一个小型服务器组件,它可以采用图像的 base64 表示并返回一个“正常”的 png 图像,我将能够将其复制到剪贴板。这可以作为一种解决方法吗?

Edit:To clearify: I'm using canvas.toDataURL("image/png", 0.7)to create an image from the canvas and I then set the srcattribute of an imgtag 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.

编辑:清除:我使用canvas.toDataURL("image/png", 0.7)从画布创建图像,然后将标签的src属性设置img为结果。然后我可以在右键单击图像时从上下文菜单中选择“复制图像”。问题是我无法将图像粘贴到 Word 和电子邮件中(至少是 Outlook)。粘贴到写字板和 mspaint 工作正常。

回答by df1

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

您可以将画布转换为img,放入 a 中<div contenteditable>,选择它并复制它。

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

SelectText 函数来自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);
    }
}

回答by Adriano Tumminelli

Clipboard API for images are now available on chrome

用于图像的剪贴板 API 现在可在 chrome 上使用

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

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

回答by Konstantinos

Much easier 1 liner:
Assuming u have a canvas.
The following code will copy the canvas (as blob --> PNG image) to your clipboard.

更容易 1 班轮:
假设你有一个画布。
以下代码将画布(作为 blob --> PNG 图像)复制到剪贴板。

    canvas.toBlob(blob => navigator.clipboard.write([new ClipboardItem({'image/png': blob})]));

回答by Aminadav Glickshtein

Today 4 years later, it's the most starred issue in Google Chrome. To copy images using JavaScript. And now it's possible!

4 年后的今天,这是谷歌浏览器中最受关注的问题。使用 JavaScript 复制图像。现在有可能!

Chrome 76 Beta supports it: https://blog.chromium.org/2019/06/chrome-76-beta-dark-mode-payments-new.html

Chrome 76 Beta 支持:https: //blog.chromium.org/2019/06/chrome-76-beta-dark-mode-payments-new.html

You can read the full draft here: https://www.chromestatus.com/feature/5074658793619456

你可以在这里阅读完整的草案:https: //www.chromestatus.com/feature/5074658793619456

and here: https://w3c.github.io/clipboard-apis/#async-clipboard-api

在这里:https: //w3c.github.io/clipboard-apis/#async-clipboard-api

Example:

例子:

var data = new Blob(["iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=="], {type : "image/png"});

  const clipboardItemInput = new ClipboardItem({'image/png' : blobInput});
  await navigator.clipboard.write([clipboardItemInput]);

You can test it here: http://w3c-test.org/clipboard-apis/async-write-image-read-image-manual.https.html

你可以在这里测试:http: //w3c-test.org/clipboard-apis/async-write-image-read-image-manual.https.html

(Now it support only Chrome 76 beta)

(现在只支持 Chrome 76 测试版)

More info: The draft document [contain examples]: https://docs.google.com/document/d/1lpi3-9vBP_1b7hZc2xBs0s_HaACJ6UigZZqHlJSNeJg/edit#heading=h.do75bvtsde7a

更多信息:文档草案[包含示例]:https: //docs.google.com/document/d/1lpi3-9vBP_1b7hZc2xBs0s_HaACJ6UigZZqHlJSNeJg/edit#heading=h.do75bvtsde7a