js 复制图片到剪切板
作者:互联网
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
标签:canvas,const,clipboard,img,ctx,js,复制,blob,剪切板 来源: https://blog.csdn.net/TooManyDdficulty/article/details/120140406