这个方法目前受限与js的API的限制,只能针对jpg/jpeg/png进行粘贴,gif目前没有比较好的方法可以去粘贴,现将代码粘贴如下:
// 通过 Canvas,我们可以将图像绘制到画布上,然后将其转换为支持的格式(如 PNG),这样就能顺利地复制到剪贴板。
async function copyImageToClipboard(imageUrl) { const response = await fetch(imageUrl); const contentType = response.headers.get('Content-Type') || 'image/png'; const isSupportedImageType = contentType.startsWith('image/'); if (!isSupportedImageType) { throw new Error('Unsupported image type'); } const blob = await response.blob(); // 获取图像的 Blob 对象const imgElement = new Image(); // 创建 Image 对象imgElement.src = URL.createObjectURL(blob); // 将 Blob 转为 URLreturn new Promise((resolve, reject) => {imgElement.onload = async () => {const canvas = document.createElement('canvas'); // 创建 Canvasconst ctx = canvas.getContext('2d'); // 获取 Canvas 上下文if (contentType === 'image/gif') {// 处理 GIF,直接使用 GIF Blobconst item = new ClipboardItem({ 'image/gif': blob }); // 使用 GIF 格式await navigator.clipboard.write([item]); // 写入剪贴板resolve();} else {// 处理 JPG/JPEG/PNG,转换为 PNGcanvas.width = imgElement.width; // 设置宽度canvas.height = imgElement.height; // 设置高度ctx.drawImage(imgElement, 0, 0); // 将图像绘制到 Canvas// 转换为 Blob,使用 'image/png' 作为 MIME 类型canvas.toBlob(async (newBlob) => {const item = new ClipboardItem({ 'image/png': newBlob }); // 使用 PNG 格式await navigator.clipboard.write([item]); // 写入剪贴板resolve(); // Promise 成功}, 'image/png');}};imgElement.onerror = reject; // 处理错误});
}