html2canvas的使用:vue中将div导出成图片
1.npm i html2canvas --save
2.导出
div内的图片需要是本地的,线上图片需要转化为base64
<script>
import html2canvas from 'html2canvas'
export default {
methods: {
//截屏
handleOk() {
html2canvas(this.$refs.screen, {
useCORS: true,
}).then((canvas) => {
if (navigator.msSaveBlob) {
// IE10+
let blob = canvas.msToBlob()
return navigator.msSaveBlob(blob, name)
} else {
let imageurl = canvas.toDataURL('image/png')
//这里需要自己选择命名规则
let imagename = ''
this.fileDownload(imageurl, imagename)
}
})
},
//下载截屏图片
fileDownload(downloadUrl, downloadName) {
let aLink = document.createElement('a')
aLink.style.display = 'none'
aLink.href = downloadUrl
aLink.download = `${downloadName}.jpg`
// 触发点击-然后移除
document.body.appendChild(aLink)
aLink.click()
document.body.removeChild(aLink)
},
},
}
</script>