复制文字:
Copy () {
navigator.clipboard.writeText('fuzhifuzhi').then(
() => {
this.$message.success('复制成功!')
},
() => {
this.$message.error('复制失败!')
}
)
}
复制图片:
步骤:1、图片base64。2、base64转blob。3、copy
// 图片元素转base64
getBase64Image(img) {
let canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext('2d');
ctx?.drawImage(img, 0, 0, img.width, img.height);
let dataURL = canvas.toDataURL('image/png');
return dataURL;
},
// base64图片转为blob
getBlobImage(dataurl) {
let arr = dataurl.split(',');
let mime = arr[0].match(/:(.*?);/)[1];
let bstr = atob(arr[1]);
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
},
// 复制图片
copy(dom, cb) {
let dataurl = this.getBase64Image(dom);
let blob = this.getBlobImage(dataurl);
navigator.clipboard.write([
new window.ClipboardItem({
[blob.type]: blob
})
]).then(function() {
if (typeof cb === 'function') {
cb();
}
}, function() {
console.log('图片复制失败!');
});
}