vue-element使用html2canvas实现网页指定区域(指定dom元素)截图

直接上代码:

复制代码
<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 = true
      this.$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 * 2
      canvas.height = height * 2
      canvas.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 图片格式转成 base64
        let dataURL = canvas.toDataURL("image/png")
        console.log(dataURL)
      })
    },
  }
</script>

**

注意注意注意:

如果要截取的dom元素、区域涉及到v-if或者v-show的条件表达式时,截取的方法请在nextTick里面调用----例如: this.$nextTick(() => { this.saveImageNew() }) 否之获取dom元素的时候会获取不到!!!!!!!!

相关推荐
RaidenLiu7 分钟前
告别陷阱:精通Flutter Signals的生命周期、高级API与调试之道
前端·flutter·前端框架
非凡ghost7 分钟前
HWiNFO(专业系统信息检测工具)
前端·javascript·后端
非凡ghost9 分钟前
FireAlpaca(免费数字绘图软件)
前端·javascript·后端
非凡ghost16 分钟前
Sucrose Wallpaper Engine(动态壁纸管理工具)
前端·javascript·后端
拉不动的猪18 分钟前
为什么不建议项目里用延时器作为规定时间内的业务操作
前端·javascript·vue.js
该用户已不存在25 分钟前
Gemini CLI 扩展,把Nano Banana 搬到终端
前端·后端·ai编程
地方地方26 分钟前
前端踩坑记:解决图片与 Div 换行间隙的隐藏元凶
前端·javascript
jason_yang30 分钟前
vue3+element-plus按需自动导入-正确姿势
vue.js·vite·element
小猫由里香32 分钟前
小程序打开文件(文件流、地址链接)封装
前端
Tzarevich35 分钟前
使用n8n工作流自动化生成每日科技新闻速览:告别信息过载,拥抱智能阅读
前端