import html2canvas from "html2canvas";
给要截图的文件设置ref值,如果是promise异步加载,可以写一个setTimeOut,用宏异步冲掉微异步
<div ref="imageTofile">
</div>
<button @click="downloadImage()"></button>
mounted(){
//所有异步请求走完后调用,可以使用回调的方式
setTimeout(() => {
this.toImage()
})
}
建议,把创建好的url保存在data中,需要下载的时候调用,downloadImage()函数
// 页面元素转图片
toImage () {
// 手动创建一个 canvas 标签
const canvas = document.createElement("canvas")
// 获取父标签,意思是这个标签内的 DOM 元素生成图片
// imageTofile是给截图范围内的父级元素自定义的ref名称
let canvasBox = this.$refs.imageTofile
// 获取父级的宽高
const width = parseInt(window.getComputedStyle(canvasBox).width)
const height = parseInt(window.getComputedStyle(canvasBox).height)
// 宽高 * 2 并放大 2 倍 是为了防止图片模糊
canvas.width = width * 1
canvas.height = height * 1
canvas.style.width = width + 'px'
canvas.style.height = height + 'px'
const context = canvas.getContext("2d");
context.scale(2, 2);
const options = {
backgroundColor: 'white', //截图背景,不给则无
useCORS: true, //允许跨域,比如有的请求或者图片会跨域,建议都设置为true
scale: 1, //放大倍数
height: document.getElementById('touched').scrollHeight, //宽高为全屏
windowHeight: document.getElementById('touched').scrollHeight,//宽高为全屏
}
html2canvas(canvasBox, options).then((canvas) => {
// toDataURL 图片格式转成 base64
let dataURL = canvas.toDataURL("image/png")
this.dataUrl = dataURL
})
},
//图片下载并导出
downloadImage(url) {
// 如果是在网页中可以直接创建一个 a 标签直接下载
let a = document.createElement('a')
a.href = url
a.download = '打印图片'
a.click()
}