如何在Vue JS中使用html2canvas?

y3bcpkx1  于 2022-12-14  发布在  Vue.js
关注(0)|答案(3)|浏览(227)

我面临的第一个障碍是Vue中没有document.getElementById的简写,所以我实现了function like this one。我面临的第二个障碍是,恕我直言,在处理没有<!DOCTYPE html><body>的情况时,html2canvas docs非常有限。
下面是我的.vue文件中的标记摘要:

<template>
   <div>
      <md-layout>
         <div id="capture" class='m1 '>
            // more markup...
         </div>
      </md-layout>
   </div>
</template>

这就是我尝试实现捕获函数的方式:

//Vue equivalent for document.getElementById
showCaptureRef() {
   console.log(this.$refs.capture);
},
// Screen capture function
downloadVisualReport () {
  let vc = this
  alert("Descargando reporte visual")
  html2canvas(vc.showCaptureRef).then(canvas => {
      vc.document.body.appendChild(canvas)
  }).catch((error) => {
    console.log("Erorr descargando reporte visual")
    alert("Error descargando el reporte visual")
  });
},
j5fpnvbx

j5fpnvbx1#

我发现我犯了两个错误:
首先,我用id='capture'代替了ref="capture"
第二,这一行vc.document.body.appendChild(canvas),需要更改为document.body.appendChild(canvas)
下面是将画布作为图像下载的函数的最终代码:

downloadVisualReport () {
  let vc = this
  let filename = 'Reporte de ' + vc.campaign.name + '.png'; 
  html2canvas(vc.showCaptureRef()).then(canvas => {  
      vc.saveAs(canvas.toDataURL(), filename);      
  }).catch((error) => {
    alert("Error descargando el reporte visual")
  });
},
moiiocjp

moiiocjp2#

对于未来的读者。试试这个vue-html2canvas mixin。

<template>
  <div>
    <!-- SOURCE -->
    <div ref="printMe">
      <h1>Print me!</h1>
    </div>
    <!-- OUTPUT -->
    <img :src="output">
  </div>
<teplate>

<script>
export default {
  data() {
    return {
      output: null
    }
  },
  methods: {
    print() {
      const el = this.$refs.printMe;
      // add option type to get the image version
      // if not provided the promise will return 
      // the canvas.
      const options = {
        type: 'dataURL'
      }
      this.output = await this.$html2canvas(el, options);
    }
  }
}
</script>
hyrbngr7

hyrbngr73#

https://www.npmjs.com/package/vue-html2canvas
  
  <template>
      <div>
        <!-- SOURCE -->
        <div ref="printMe">
          <h1>Print me!</h1>
        </div>
        <!-- OUTPUT -->
        <img :src="output">
      </div>
    <teplate>
    
    <script>
    export default {
      data() {
        return {
          output: null
        }
      },
      methods: {
        print() {
          const el = this.$refs.printMe;
          // add option type to get the image version
          // if not provided the promise will return 
          // the canvas.
          const options = {
            type: 'dataURL'
          };
          (async () => {
              this.output = await this.$html2canvas(el, options);
          })()
        }
      }
    }
    </script>

相关问题