实现图片的复制和粘贴
首先有一张图,然后一个按钮作为交互,点击复制图片
代码如下
const testImg = document.getElementById('img1');
const copyBtn = document.getElementById('copyBtn')
function handleCopyImg() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
canvas.width = testImg.width;
canvas.height = testImg.height;
img.crossOrigin = "Anonymous";
img.src = testImg.src;
img.onload = () => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img, 0, 0);
// 将canvas转为blob
canvas.toBlob(async blob => {
console.log(blob);
const data = [new ClipboardItem({ [blob.type]: blob, }),];
// https://w3c.githu