下载依赖包 npm install --save html2canvas
// 引用依赖包
import html2canvas from 'html2canvas'
const dataURLToBlob = (dataurl) => {
const arr = dataurl.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
const u8arr = new Uint8Array(n)
let n = bstr.length
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], {type: mime})
}
// imgName:图片名称,canvasRef:div代码块
const saveImage = (imgName, canvasRef) => {
const a = document.createElement('a')
html2canvas(canvasRef).then(canvas => {
const dom = document.body.appendChild(canvas)
dom.style.display = 'none'
a.style.display = 'none'
document.body.removeChild(dom)
const blob = dataURLToBlob(dom.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)
})
}
// 使用
saveImage ('temp', document.querySelector('.canvas'))