二维码 内嵌图片,下载二维码

功能

  • 二维码可内嵌图片
  • 可下载二维码
  • 功能集合成Vue组件

使用技术

  • Vue、qrcodejs2、html2canvas

直接上代码

<template>
  <div class="qr" ref="pic">
    <img v-if="imgUrl" class="my-image" :src="imgUrl" alt="">
    <div ref="qrcode"></div>
  </div>
</template>
<script>
import QRCode from "qrcodejs2";
import html2canvas from 'html2canvas';
export default {
  name: 'my-qrcode',
  props: {
    imgUrl: {
      type: String,
      default: ''
    },
    height: {
      type: Number,
      default: 100
    },
    width: {
      type: Number,
      default: 100
    },
    text: {
      type: String,
      default: '测试文字'
    }
  },
  mounted () {
  },
  watch: {
    text: {
      handler () {
        this.$nextTick(() => {
          this.load()
        })
      },
      immediate: true
    }
  },
  methods: {
    load () {
      // const text = params + "动态解析内容";
      // console.log(text, 'text');
      if (this.qrCode) {
        //单例 如果需要重复点击生成携带不同text内容的二维码,则需要通过这种方式
        //先清除 然后在使用makeCode重新更换 text内容
        //不然重复点击后下载的内容是最后一次点击的text,
        this.qrCode.clear();
        this.qrCode.makeCode(this.text);
      } else {
        this.qrCode = new QRCode(this.$refs.qrcode, {
          width: this.width,
          height: this.height,
          text: this.text,
          colorDark: "#000",
          colorLight: "#fff",
        });
      }
    },
    convertToImage (container) {
      // 2. 传入节点原始宽高
      const _width = container.offsetWidth;
      const _height = container.offsetHeight;
      // 3. html2canvas配置项
      const ops = {
        _width,
        _height,
        useCORS: true,
        allowTaint: false,
      };
      return html2canvas(container, ops).then(canvas => {
        // 4. 返回图片的二进制数据
        return canvas.toDataURL("image/png");
      });
    },
    // 下载二维码 给父组件调用
    download (name) {
      // 调用函数获取图片路径
      let picDom = this.$refs.pic
      this.convertToImage(picDom).then(res => {
        // 将图片下载到本地
        var x = new XMLHttpRequest();
        x.open("GET", res, true);
        x.responseType = 'blob';
        x.onload = function () {
          var url = window.URL.createObjectURL(x.response)
          var a = document.createElement('a');
          a.href = url
          a.download = name || '自定义图片名'
          a.click()
        }
        x.send();
      })
    }
  }
}
</script>
<style  scoped>
.qr {
  position: relative;
  display: inline-block;
}
.my-image {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  width: 25px;
  height: 25px;
  background: #FFF;
  padding: 5px;
  margin: auto;
}
</style>

猜你喜欢

转载自blog.csdn.net/weixin_49070128/article/details/126657233