import html2Canvas from 'html2Canvas'
import waterMark from 'watermark.js' // 引入添加水印方法 导出图片可以添加水印
exportImg(){
let imgDom = document.querySelector('.pircture') // 导出图片dom
let imgName = '图片'
let width = imgDom.scrollWidth
let height = imgDom.scrollHeight
let opts = {
scale:2,
height,
width,
useCORS:true, // 开启跨域配置
}
html2Canvas(imgDom,opts).then((canvas) => {
canvas = waterMark.spreadMarkScreen(canvas,'lisi',15,width,height,10,10,100,50) // 图片添加水印
let a = document.createElement('a')
a.style.display = 'none'
let blob = this.dataURLToBlob(canvas.toDataURL('image/png'))
a.setAttribute('href',URL.createObjectURL(blob))
a.setAttribute('download',imgName+'.png')
document.body.appendChild(a)
a.click()
URL.revokeObjectURL(blob)
document.body.removeChild(a)
})
}
dataURLToBlob(dataUrl){
let arr = dataUrl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Unit8Array(n),
while(n--){
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr],{type:mime})
}
html2Canvas导出图片
于 2022-12-19 14:31:48 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)