copyImg.js
const handleCopyImg = (imgSrc, callback, imgWidth = '100', imgHeight = '100') => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
canvas.width = imgWidth;
canvas.height = imgHeight;
img.crossOrigin = 'Anonymous';
img.src = imgSrc;
img.onload = () => {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.drawImage(img, 0, 0, imgWidth, imgHeight);
// 将canvas转为blob
canvas.toBlob(async (blob) => {
console.log(blob);
const data = [
// eslint-disable-next-line no-undef
new ClipboardItem({
[blob.type]: blob,
}),
];
await navigator.clipboard.write(data)
.then(
() => {
console.log('Copied to clipboard successfully!');
callback();
},
() => {
console.error('Unable to write to clipboard.');
}
);
});
};
};
export default handleCopyImg;
这个方法可以进行图片的复制,但是会有一些兼容问题(比如说ie完全不兼容,以及一些浏览器低版本也不支持)
使用的时候需要注意,navigator.clipboard 需要在安全域下使用 (https 的站点下)
本文参考自:https://juejin.cn/post/6909379124679311368