正在React Web应用程序上工作,需要实现的功能之一是单击时复制图像,以便用户可以将其粘贴到:绘画,文字等...
我尝试了几种方法,首先是按照本文中详细介绍的说明进行操作:https://stackoverflow.com/a/40547470/9608006
这是我想出的(containerId表示一个div元素,其中包含一个image元素作为其第一个子元素):
copyImg = (containerId) => {
const imgContainerElement = document.getElementById(containerId);
this.selectText(imgContainerElement.children[0]);
document.execCommand('copy');
window.getSelection().removeAllRanges();
alert('image copied!');
}
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);
}
}
没有用。 我尝试在此处实施标有2星的解决方案:https://www.tek-tips.com/viewthread.cfm?qid=833917
function copyImg(imgId){
var r = document.body.createControlRange();
r.add(document.getElementById(imgId));
r.select();
r.execCommand("COPY");
}
但是未定义createControlRange()。
我尝试使用navigator.clipboard API,但仅适用于png,而该应用程序适用于jpg。
我正在寻找一个可以完成此任务的npm库,但是我发现的只是用于文本复制。 npms就像:react-copy-to-clipboard
任何帮助将不胜感激。
编辑1:
按照dw _ https://stackoverflow.com/a/59183698/9608006的说明,这是我想到的: (注意:我必须npm安装babel-polyfill并将其导入App.js中,以使异步功能正常工作并传递此错误:regeneratorRuntime未定义)
copyImg = async (imgElementId) => {
const imgElement = document.getElementById(imgElementId);
const src = imgElement.src;
const img = await fetch(src);
const imgBlob = await img.blob();
if (src.endsWith(".jpg") || src.endsWith(".jpeg")) {
copyService.convertToPng(imgBlob);
} else if (src.endsWith(".png")) {
copyService.copyToClipboard(imgBlob);
} else {
console.error("Format unsupported");
}
}
convertToPng = (imgBlob) => {
const imageUrl = window.URL.createObjectURL(imgBlob);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const imageEl = createImage({ src: imageUrl });
imageEl.onload = (e) => {
canvas.width = e.target.width;
canvas.height = e.target.height;
ctx.drawImage(e.target, 0, 0, e.target.width, e.target.height);
canvas.toBlob(copyToClipboard, "image/png", 1);
};
}
createImage = (options) => {
options = options || {};
const img = (Image) ? new Image() : document.createElement("img");
if (options.src) {
img.src = options.src;
}
return img;
}
copyToClipboard = (pngBlob) => {
try {
navigator.clipboard.write([
new ClipboardItem({
[pngBlob.type]: pngBlob
})
]);
console.log("Image copied");
} catch (error) {
console.error(error);
}
}
该代码到达“已复制图像”消息,但是将其粘贴到单词上时仍未显示。另外一件事是我得到
控制台错误:未捕获(承诺)的DOMException
答案 0 :(得分:1)
基于@Zohaib Ijaz的回答和Convert JPG images to PNG using HTML5 URL and Canvas文章。
如果图像是jpeg / jpg,它将首先使用HTML5画布将图像转换为png。
function createImage(options) {
options = options || {};
const img = (Image) ? new Image() : document.createElement("img");
if (options.src) {
img.src = options.src;
}
return img;
}
function convertToPng(imgBlob) {
const imageUrl = window.URL.createObjectURL(imgBlob);
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const imageEl = createImage({ src: imageUrl });
imageEl.onload = (e) => {
canvas.width = e.target.width;
canvas.height = e.target.height;
ctx.drawImage(e.target, 0, 0, e.target.width, e.target.height);
canvas.toBlob(copyToClipboard, "image/png", 1);
};
}
async function copyImg(src) {
const img = await fetch(src);
const imgBlob = await img.blob();
if (src.endsWith(".jpg") || src.endsWith(".jpeg")) {
convertToPng(imgBlob);
} else if (src.endsWith(".png")) {
copyToClipboard(imgBlob);
} else {
console.error("Format unsupported");
}
}
async function copyToClipboard(pngBlob) {
try {
await navigator.clipboard.write([
new ClipboardItem({
[pngBlob.type]: pngBlob
})
]);
console.log("Image copied");
} catch (error) {
console.error(error);
}
}
function copyImageViaSelector(selector) {
copyImg(document.querySelector(selector).src);
}
<img id="image" width="100" src="https://i.imgur.com/Oq3ie1b.jpg">
<button onclick="copyImageViaSelector('#image')">Copy image</button>
反应:
import React, { useRef } from "react";
const createImage = (options) => {
options = options || {};
const img = document.createElement("img");
if (options.src) {
img.src = options.src;
}
return img;
};
const copyToClipboard = async (pngBlob) => {
try {
await navigator.clipboard.write([
// eslint-disable-next-line no-undef
new ClipboardItem({
[pngBlob.type]: pngBlob
})
]);
console.log("Image copied");
} catch (error) {
console.error(error);
}
};
const convertToPng = (imgBlob) => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const imageEl = createImage({ src: window.URL.createObjectURL(imgBlob) });
imageEl.onload = (e) => {
canvas.width = e.target.width;
canvas.height = e.target.height;
ctx.drawImage(e.target, 0, 0, e.target.width, e.target.height);
canvas.toBlob(copyToClipboard, "image/png", 1);
};
};
const copyImg = async (src) => {
const img = await fetch(src);
const imgBlob = await img.blob();
const extension = src.split(".").pop();
const supportedToBeConverted = ["jpeg", "jpg", "gif"];
if (supportedToBeConverted.indexOf(extension.toLowerCase())) {
return convertToPng(imgBlob);
} else if (extension.toLowerCase() === "png") {
return copyToClipboard(imgBlob);
}
console.error("Format unsupported");
return;
};
const Image = () => {
const ref = useRef(null);
return (
<div>
<img id="image" ref={ref} width="100" src="https://i.imgur.com/Oq3ie1b.jpg" alt="" />
<button onClick={() => copyImg(ref.current.src)}>copy img</button>
</div>
);
};
export default Image;
已知限制:
答案 1 :(得分:0)
您可以使用navigator.clipboard.write
function async copyImg (src) {
const img = await fetch(src);
const imgBlob = await img.blob();
try {
navigator.clipboard.write([
new ClipboardItem({
'image/png': imgBlob, // change image type accordingly
})
]);
} catch (error) {
console.error(error);
}
}
答案 2 :(得分:0)
您可以尝试一下。您需要为此提供一个HTMLDivElement。
通常是对某个div的引用。
<div ref={node => (this._imageRef = node)}>
<img src=""/>
</div>
您可以在构造函数中将此红色初始化为
constructor(props) {
super(props);
this._imageRef = null;
}
您需要将此_imageRef提供给函数。
现在所有这些都应该起作用。
export function copyImageToClipboard(element) { // element is an ref to the div here
const selection = window.getSelection();
const range = document.createRange();
const img = element.firstChild ;
// Preserve alternate text
const altText = img.alt;
img.setAttribute('alt', img.src);
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
try {
// Security exception may be thrown by some browsers.
return document.execCommand('copy');
} catch (ex) {
console.warn('Copy to clipboard failed.', ex);
return false;
} finally {
img.setAttribute('alt', altText);
}
}
注意:这也适用于IE