JavaScript
主页 > 网络编程 > JavaScript >

基于原生javaScript生成带图片的二维码

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

<div class="qr_code">
  <img src="" id="imgcode" />
  <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
 }

原文链接:https://www.cnblogs.com/muzimumu/p/10819645.html
相关文章
最新更新