使用原生javaScript绘制带图片的二维码---js

使用链接生成二维码主要是使用qr.js或者其他,把链接转化为二维码的形式,在使用canvas时需要设置画布的尺寸,生成的颜色。

<div class="qr_code">
   <img src=""   />
   <canvas ref="canvas" hidden></canvas>
<div>

js

   function createQr () { // 生成带图片二维码
     const qrcode = qr('http://baidu.com') // 转化链接
     const canvas = this.$refs.canvas
     const ctx = canvas.getContext('2d')
     const size = 128 / qrcode.moduleCount  //128设置的二维码尺寸
     const scale = window.devicePixelRatio / getPixelRatio(ctx)
     canvas.height = canvas.width = 128e * scale
     ctx.scale(scale, scale)
     qrcode.modules.forEach((row, rdx) => {
       row.forEach((cell, cdx) => {
         ctx.fillStyle = cell ? '#000' : '#fff' // 设置二维码颜色和背景颜色
         var w = (Math.ceil((cdx + 1) * size) - Math.floor(cdx * size))
         ctx.fillRect(Math.round(cdx * size), Math.round(rdx * size), w, w)
       })
     })
     var image = document.createElement('img')
     var imgcode =   document.getElementById('imgcode')
     image.src = 'http://baidu/logo.png' //二维码中间图标
     image.onload = () => {
        var dwidth = 128 * 0.2 // 设置图片大小
        var dx = (128 - dwidth) / 2
        var dheight = image.height / image.width * dwidth
        var dy = (this.size - dheight) / 2
        image.width = dwidth
        image.height = dheight
        ctx.drawImage(image, dx, dy, dwidth, dheight)
        imgcode.src = canvas.toDataURL()
     }
  },
  getPixelRatio (ctx) {
     return ctx.webkitBackingStorePixelRatio || ctx.backingStorePixelRatio || 1
  }

以上是实现生成带二维码的图片代码,可以直接使用。