vue html2canvas + qrcode 画分享图

安装

  npm install html2canvas --save  
  npm install qrcodejs2 --save  //二维码

引入

  import html2canvas from 'html2canvas'
  import QRCode from 'qrcodejs2';

生成二维码

<div id="qrCode" ref="qrCodeDiv" v-if="isDom"></div>
  qrCode() {
      new QRCode(this.$refs.qrCodeDiv, {  //this.$refs.qrCodeDiv生成二维码的dom
        text: xxx, //二维码地址
        width: 125,
        height: 125,
        colorDark: "#333333", //二维码颜色
        colorLight: "#ffffff", //二维码背景色
        correctLevel: QRCode.CorrectLevel.L//容错率,L/M/H
      })
    },

把生成的二维码和海报图样式写好之后就用html2canvas生成图片

// 画图区域
<div class="share" id="html2canvas" ref="html2canvas">
   <img :src="ewm" alt="" v-if="isDom" >
   <div id="qrCode" ref="qrCodeDiv" v-if="isDom"></div>
</div>
shareImage() {
      var targetDom = this.$refs.html2canvas //画图区域的dom
      html2canvas(targetDom, {
        allowTaint: false,
        useCORS: true,
        height: targetDom.offsetHeight,
        width: targetDom.offsetWidth,
        taintTest: true, // 在渲染前测试图片
        timeout: 500, // 加载延时
        windowWidth: document.body.scrollWidth,
        windowHeight: document.body.scrollHeight,
        dpi: window.devicePixelRatio * 2,
        scale: 2
        // backgroundColor: 'rgb(213,201,221)'
      }).then(canvas => {
        this.$refs.html2canvas.append(canvas);//在下面添加canvas节点
        this.isDom = false
        let link = document.createElement("a");
        link.href = canvas.toDataURL();//下载链接
        link.setAttribute("download","体检表.png");
        link.style.display = "none";//a标签隐藏
        document.body.appendChild(link);
        // link.click(); // 直接触发下载事件   看需求是否需要
      })
    },
mouted() {
  getCode() {
      this.isDom = true
      /** f (this.$refs.html2canvas) {
        this.$refs.html2canvas.removeChild(this.$refs.html2canvas.lastChild)
      } 
      防止每次重复生成二维码*/
      this.$nextTick(() => {
        this.qrCode()
        setTimeout(() => {
          this.shareImage()  //生成的时候需要放在定时器里面  防止生成的海报画图有偏差,如果有白边可以尝试把定时器的时间延长
        }, 200)
      })
    },
}

github地址
https://github.com/niklasvh/html2canvas

推荐阅读更多精彩内容