安装包
npm install --save qrcodejs2 npm install --save html2canvas
HTML
<div class="scan"> <div ref="imageDom" class="qrBox" v-if="isQRCode"> <img class="qrbj" src="../../assets/img/qrbg.png"> <div class="qrCon"> <div class="qrTitle">扫码关注旗帜</div> <div class="qrCanvas"> <div class="qrBorder"><div id="qrcode" style="width: 150px;height:150px"></div></div> </div> </div> </div> <img v-else :src="imgUrl" class="qrImg"> </div>
JS
import QRCode from ‘qrcodejs2‘ import html2canvas from ‘html2canvas‘ export default { data () { return { isQRCode: true, imgUrl: ‘‘ } }, mounted () { this.qrcode(‘https://img0.baidu.com/it‘) }, methods: { /* 扫码签名 */ qrcode (text) { // 生成二维码 let qrcode = new QRCode(‘qrcode‘, { width: 150, height: 150 }) qrcode.makeCode(text) this.clickGeneratePicture() }, /** * 将页面指定节点内容转为图片 * 1.拿到想要转换为图片的内容节点DOM; * 2.转换,拿到转换后的canvas * 3.转换为图片 */ clickGeneratePicture () { // 生成图片 // var canvas = document.createElement(‘canvas‘) // canvas.getContext(‘2d‘).scale(1, 1) html2canvas(this.$refs.imageDom).then(canvas => { // 转成图片,生成图片地址 this.isQRCode = false this.imgUrl = canvas.toDataURL(‘image/png‘) // 可将 canvas 转为 base64 格式 }) } } }
效果图