首先需要安装插件
npm install html2canvas
导入插件:
import html2canvas from 'html2canvas'
事件:
downloadImg('jpg')
downloadImg('png')
逻辑:
// 下载图片
downloadImg (type) {
html2canvas(document.querySelector('需导出的结构类名')).then(canvas => {
const url = canvas.toDataURL(`image/${type}`)
const imgEle = new Image()
imgEle.src = url
imgEle.onload = () => {
const a = document.createElement('a')
a.href = url
a.download = `导出名称.${type === 'jpeg' ? 'jpg' : type}`
// 触发a链接点击事件,浏览器开始下载文件
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
})
}