使用連接生成二維碼主要是使用qr.js或者其餘,把連接轉化爲二維碼的形式,在使用canvas時須要設置畫布的尺寸,生成的顏色。git
<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 }
以上是實現生成帶二維碼的圖片代碼,能夠直接使用。github