vue 如何将链接或者文字通过qrcodejs2插件转为二维码,以及中间增加logo

1、首先需要安装qrcodejs2插件

yarn add qrcodejs2

2、需在html里面定义一个用于渲染二维码的标签元素

<div ref="qrcode" style="display: none"></div>
<img v-if="qrcodeSrc" :src="qrcodeSrc" class="qr-code" />

3、开始处理转换

created() {
    const miniPath = window.location.origin + `/bank.html#/apply?bankCode=${this.$route.query.bankCode}&channelCode=${this.$route.query.channelCode}`;
    this.$nextTick(() => {
      this.qrcode(miniPath);
    });
  },
methods: {
    qrcode(text) {
      if (!text) return;
      this.$refs.qrcode.innerHTML = "";
      // eslint-disable-next-line no-unused-vars
      const qrcode = new QRCode(this.$refs.qrcode, {
        width: 200,
        height: 200, // 高度
        text: text, // 二维码内容
        render: "canvas", // 设置渲染方式(有两种方式 table和canvas,默认是canvas)
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H,
      });
      this.$nextTick(() => {
        setTimeout(() => {
          this.downImage();
        });
      });
    },

    downImage() {
      const canvas = this.$refs.qrcode.querySelector("canvas");
      const img = canvas.toDataURL("image/png");
      this.$refs.qrcode.innerHTML = "";
      this.qrcodeSrc = img;
    }
  },

 style:

.qr-code {
    width: 200px;
    height: 200px;
    object-fit: cover;
  }

如何在生成的二维码中间增加logo呢downImage方法即可。

先定义logo的地址,然后在onload方法里面获取到canvas,通过调用drawImage的api将图片定位到画布的中间。

downImage() {
        const logo= document.createElement("img");
        logo.setAttribute("crossOrigin", "Anonymous");
        logo.src = require("../common/image/pic1/ggl16.png");
        logo.onload = () => {
          const canvas = this.$refs.qrcode.querySelector("canvas");
          let cxt = canvas.getContext('2d');
          const width = canvas.width / 2 - logo.height / 2;
          const height = canvas.height / 2 - logo.height / 2;
          cxt.drawImage(logo, width, height,44,44);
          const img = canvas.toDataURL("image/png");
          this.$refs.qrcode.innerHTML = "";
          this.qrcodeSrc = img;
        }
    }           

 

posted @ 2023-08-15 11:28  wjs0509  阅读(593)  评论(0编辑  收藏  举报