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元素的时候会获取不到!!!!!!!!

相关推荐
紫_龙7 分钟前
最新版vue3+TypeScript开发入门到实战教程之生命周期函数
前端·javascript·typescript
小江的记录本15 分钟前
【反射】Java反射 全方位知识体系(附 应用场景 + 《八股文常考面试题》)
java·开发语言·前端·后端·python·spring·面试
孟陬15 分钟前
国外技术周刊 #4:这38条阅读法则改变了我的人生、男人似乎只追求四件事……
前端·人工智能·后端
工边页字17 分钟前
cursor接上figma mcp ,图形图像模式傻瓜式教学(包教包会版)
前端·人工智能·ai编程
callJJ18 分钟前
Ant Design Table 批量操作踩坑总结 —— 从三个 Bug 看前端表格开发的共性问题
java·前端·经验分享·bug·管理系统
我去流水了25 分钟前
【独家免费】【亲测】在linux下嵌入式linux的web http服务【Get、Post】,移植mongoose,post上传文件
linux·运维·前端
Mintopia29 分钟前
世界头部大厂的研发如何使用 AI-Coding?
前端
wuhen_n29 分钟前
响应式图片的工程化实践:srcset与picture
前端·javascript·vue.js
学博成31 分钟前
centos7.9 安装 Firefox
前端·firefox
wuhen_n32 分钟前
CDN图片服务与动态参数优化
前端·javascript·vue.js