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

相关推荐
inquisiter6 分钟前
KernelGpt的部分尝试
java·前端·apache
the局外人28 分钟前
用 TRAE 把 Markdown文档 搬到微信公众号
前端
Autumn_ing29 分钟前
AI原型设计工具怎么选?可编辑原型与可运行前端适合什么场景
前端·小程序·产品经理·代码·codex·墨刀ai客户端·ai原型
夕阳_醉了1 小时前
前端通用组件开发全指南|从 0 到 1 打造稳定可复用的业务组件
前端
Amos_Web1 小时前
Rspack 源码解析(三十):SourceMapDevToolPlugin 如何生成并关联 source map
前端
console.log('npc')1 小时前
从0到1实现任务评价统计功能:React + TypeScript 实战指南(小白注释版)
前端·react.js·typescript
IT_陈寒1 小时前
为什么你应该学习React?
前端·人工智能·后端
ZoeLandia1 小时前
React04:事件处理与受控表单
开发语言·前端·react.js·typescript
亿元程序员1 小时前
用AI做了一款微信小游戏,却发现上传不了
前端
Ai-_Man2 小时前
我需要批量导出Poe左边栏所有对话,而不是一条具体的对话内容,你们AI导出鸭可以吗?
开发语言·前端·javascript·人工智能·小程序