<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue使用qrcodejs绘制二维码</title>
<script src="https://cdn.bootcdn.net/ajax/libs/qrcodejs/1.0.0/qrcode.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6/dist/vue.min.js"></script>
<style>
.qrCode {
border-radius: 10px;
box-shadow: 0 0 2px 3px #eeeeee;
padding: 10px;
margin: 10px auto;
}
.title {
text-align: center;
}
.qrCodeContainer {
margin: auto;
width: 300px;
height: 300px;
}
/* 重写二维码尺寸 */
.qrCodeContainer canvas+img {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="app">
<div class="qrCode" v-for="(item, index) in cardId" :key="index">
<p class="title" v-text="item"></p>
<div class="qrCodeContainer" :ref="'qrCodeDiv'+index"></div>
</div>
</div>
<script>
new Vue({
el: '#app',
data: {
cardId: ['Cheryl71', 'Daaayyy71']
},
mounted() {
this.$nextTick(() => {
for (let i = 0; i < this.cardId.length; i++) {
this.creatQrCodeArray(i, this.cardId[i])
}
})
},
methods: {
creatQrCodeArray(index, cardId) {
let key = 'qrCodeDiv' + index;
let tmp = document.createElement('div');
let qrcode = new QRCode(tmp, {
text: cardId,
width: 162,
height: 162,
colorDark: "#333333", //二维码颜色
colorLight: "#ffffff", //二维码背景色
correctLevel: QRCode.CorrectLevel.L //容错率,L/M/H
})
let logo = new Image();
logo.crossOrigin = 'Anonymous';
logo.src = "https://img2.baidu.com/it/u=3765512519,3278388264&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500"
let that = this;
let con = this.$refs[key][0];
logo.onload = function() {
let container = con;
let qrImg = qrcode._el.getElementsByTagName('img')[0];
let canvas = qrcode._el.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(logo, 162 * 0.5 - 22, 162 * 0.5 - 22, 44, 44);
qrImg.src = canvas.toDataURL();
container.appendChild(qrcode._el);
// 销毁临时dom
tmp = null;
qrcode = null;
logo = null;
}
}
}
})
</script>
</body>
</html>
08-15
3844
09-16