直接上代码:
<template><el-dialog :visible.sync="printDialogVisible" width="1000px" :close-on-click-modal="false" append-to-body><template><div :id="print_content" ref="print_content"><slot /></div></template></div></el-dialog>
</template><script>methods: {show() {this.printDialogVisible = truethis.$nextTick(() => {this.saveImageNew()})},saveImageNew() {let tabName = document.getElementById('print_content');// 手动创建一个 canvas 标签const canvas = document.createElement("canvas")// 获取父标签,意思是这个标签内的 DOM 元素生成图片// imageTofile是给截图范围内的父级元素自定义的ref名称let canvasBox = tabName// 获取父级的宽高const width = parseInt(window.getComputedStyle(canvasBox).width)const height = parseInt(window.getComputedStyle(canvasBox).height)// 宽高 * 2 并放大 2 倍 是为了防止图片模糊canvas.width = width * 2canvas.height = height * 2canvas.style.width = width + 'px'canvas.style.height = height + 'px'const context = canvas.getContext("2d");context.scale(2, 2);const options = {backgroundColor: null,canvas: canvas,useCORS: true}html2canvas(canvasBox, options).then((canvas) => {// toDataURL 图片格式转成 base64let dataURL = canvas.toDataURL("image/png")console.log(dataURL)})},}
</script>
**
注意注意注意:
如果要截取的dom元素、区域涉及到v-if或者v-show的条件表达式时,截取的方法请在nextTick里面调用----例如: this.$nextTick(() => { this.saveImageNew() }) 否之获取dom元素的时候会获取不到!!!!!!!!