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

这篇文章主要介绍了如何基于原生javaScript生成带图片的二维码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

使用链接生成二维码主要是使用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
 }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

若文章对您有帮助,帮忙点个赞!

0
-3
发布时间 2019-11-21 12:01:41
0 条回复(回复会通过微信通知作者)
点击加载更多评论
登录 后再进行评论
(微信扫码即可登录,无需注册)