Vue中Html2canvas生成网页局部截图
Html2canvas文档地址npm安装Html2canvasnpm install --save html2canvas项目文件引入Html2canvas(在哪使用就引入到哪)import html2canvas from 'html2canvas'使用(最后可生成png图片)<template><Buttonclass="ml-3"type="primary"icon="io
·
- npm安装Html2canvas
npm install --save html2canvas
- 项目文件引入Html2canvas(在哪使用就引入到哪)
import html2canvas from 'html2canvas'
- 使用(最后可生成png图片)
<template>
<Button
class="ml-3"
type="primary"
icon="ios-cut"
@click="saveImage('dataDiv', '截图')"
>
截屏
</Button>
<div ref="dataDiv" class="data-warp">
// 被截图区域,需要在div上设置ref
</div>
</template>
<script>
import html2canvas from 'html2canvas'
export default {
methods: {
//图片格式转换方法
dataURLToBlob(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 })
},
//点击方法
saveImage(divText, imgText) {
let canvasID = this.$refs[divText]
let that = this
let a = document.createElement('a')
html2canvas(canvasID).then((canvas) => {
let dom = document.body.appendChild(canvas)
dom.style.display = 'none'
a.style.display = 'none'
document.body.removeChild(dom)
let blob = that.dataURLToBlob(dom.toDataURL('image/png'))
a.setAttribute('href', URL.createObjectURL(blob))
//这块是保存图片操作 可以设置保存的图片的信息
a.setAttribute('download', imgText + '.png')
document.body.appendChild(a)
a.click()
URL.revokeObjectURL(blob)
document.body.removeChild(a)
})
},
}
}
</script>
更多推荐
已为社区贡献1条内容
所有评论(0)