在二维码上画LOGO图案
在二维码上画LOGO图案

<template>

 <div :id="id" :ref="id" style="width: 100%;height: 100%;text-align: center;"/>

</template>

<script>

import QRCode from 'qrcodejs2'


export default {

 props: {

  id: {

   type: String,

   required: true

  },

  text: { // 后端返回的二维码地址

   type: String,

   default: 'http://jindo.dev.naver.com/collie'

  },

  width: {

   type: String,

   default: '128'

  },

  height: {

   type: String,

   default: '128'

  },

  colorDark: {

   type: String,

   default: '#000000'

  },

  colorLight: {

   type: String,

   default: '#ffffff'

  },

  logoImage: {

   type: String,

   default: ''

  }

 },

 data () {

  return {

   qrcode: ''

  }

 },

 watch: {

  text (newText) {

   this.createQrcode()

  }

 },

 mounted () {

  this.createQrcode()

 },

 methods: {

  createQrcode () {

   if (this.qrcode) { // 有新的二维码地址了,先把之前的清除掉

    this.$refs[this.id].innerHTML = ''

   }

   this.qrcode = new QRCode(this.$refs[this.id], {

    text: this.text, // 页面地址 ,如果页面需要参数传递请注意哈希模式#

    width: this.width, // 二维码宽度 (不支持100%)

    height: this.height, // 二维码高度 (不支持100%)

    colorDark: this.colorDark,

    colorLight: this.colorLight,

    correctLevel: QRCode.CorrectLevel.H

   })

   // 添加二维码中间的图片

   if (this.logoImage) {

    let logo = new Image()

    logo.setAttribute('crossOrigin', 'Anonymous')

    logo.src = this.logoImage

    logo.onload = () => {

     let qrImg = this.qrcode._el.getElementsByTagName('img')[0]

     let canvas = this.qrcode._el.getElementsByTagName('canvas')[0]

     this.qrcode._el.title = ''

     canvas.style.display = 'inline-block'

     let ctx = canvas.getContext('2d')

     // 设置logo的大小为二维码图片缩小的3.7倍,第二与第三参数代表logo在二维码的位置

     ctx.drawImage(logo, (128 - 128 / 3.7) / 2, (128 - 128 / 3.7) / 2, 128 / 3.7, 128 / 3.7)

     qrImg.src = canvas.toDataURL()

     qrImg.style.display = 'none'

     this.$refs.id.appendChild(this.qrcode._el)

    }

   }

   console.log(this.qrcode, 'qrcode')

  },

  // 制作另一个二维码

  updateCode () {

   this.qrcode.makeCode('http://naver.com')

  }

 }

}

</script>


如果您需要更详细的了解,请用微信扫描下面的二维码添加客服的微信,我们将详细为您解答,谢谢!