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

相关推荐
国服第二切图仔38 分钟前
DevUI Design中后台产品开源前端解决方案之Carousel 走马灯组件使用指南
前端·开源
无限大61 小时前
为什么浏览器能看懂网页代码?——从HTML到渲染引擎的奇幻之旅
前端
福尔摩斯张1 小时前
Linux信号捕捉特性详解:从基础到高级实践(超详细)
linux·运维·服务器·c语言·前端·驱动开发·microsoft
2401_860319521 小时前
DevUI组件库实战:从入门到企业级应用的深度探索 ,如何快速安装DevUI
前端·前端框架
计算机毕设VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue服装商城系统(源码+数据库+文档)
数据库·vue.js·spring boot·课程设计
cc蒲公英1 小时前
javascript有哪些内置对象
java·前端·javascript
zhangwenwu的前端小站1 小时前
vue 对接 Dify 官方 SSE 流式响应
前端·javascript·vue.js
王林不想说话2 小时前
受控/非受控组件分析
前端·react.js·typescript
_杨瀚博2 小时前
VUE中使用AXIOS包装API代理
前端
张有志2 小时前
基于 Body 滚动的虚拟滚动组件技术实现
前端·react.js