vue+qrcode动态生成带logo的二维码
vue+qrcode动态生成带logo的二维码
·
目录
1、安装qrcode
npm install --save qrcode
2、配置qrcode
找到main.js添加以下配置:
//Vue使用QRCode插件,生成二维码
import QRCode from 'qrcode'
Vue.prototype.$QRCode = QRCode
3、创建二维码生成组件
<template>
<div class="qr-code-generator">
<canvas ref="qrCanvas"></canvas>
</div>
</template>
<script>
import logo from '@/assets/login/chilun.svg'
export default {
name:'qrCode',
props: {
url: {
type: String,
required: true
},
logoUrl: {
type: String,
default: logo
},
logoMargin: {
type: Number,
default: 32 // 设置 logo 周围清除的空间
}
},
data() {
return {
logoPath: logo
};
},
mounted() {
let url = "http://www.baidu.com";
this.generateQrCode(url);
},
methods: {
//生产二维码,简约方式
generateQRCode(url) {
const canvas = document.getElementById("canvas");
this.$QRCode.toCanvas(canvas, url, {width: 200}); //直接修改二维码尺寸
},
//生产二维码,中间加logo方式,默认尺寸为300*300
async generateQrCode(url) {
try {
const qrDataUrl = await this.$QRCode.toDataURL(url, { errorCorrectionLevel: 'H' });
const canvas = this.$refs.qrCanvas;
const ctx = canvas.getContext('2d');
const qrSize = 300; // QR Code 的尺寸
canvas.width = qrSize;
canvas.height = qrSize;
// 绘制二维码
const img = new Image();
img.src = qrDataUrl;
img.onload = () => {
ctx.drawImage(img, 0, 0, qrSize, qrSize);
// 清理 logo 周围的区域
const centerX = qrSize / 2;
const centerY = qrSize / 2;
ctx.globalCompositeOperation = 'destination-out'; // 设置为擦除模式
ctx.beginPath();
ctx.arc(centerX, centerY, this.logoMargin, 0, Math.PI * 2); // 清理圆区域
ctx.fill();
ctx.globalCompositeOperation = 'source-over'; // 恢复正常模式
// 绘制 logo
const logo = new Image();
logo.src = this.logoUrl;
logo.onload = () => {
const logoSize = qrSize / 5; // logo 的尺寸
const logoX = centerX - logoSize / 2; // logo 的 X 坐标
const logoY = centerY - logoSize / 2; // logo 的 Y 坐标
ctx.drawImage(logo, logoX, logoY, logoSize, logoSize);
};
};
} catch (err) {
console.error('Error generating QR code:', err);
}
}
},
};
</script>
<style>
.qr-code-generator {
display: flex;
flex-direction: column;
align-items: center;
}
</style>
4、生成的二维码
更多推荐
所有评论(0)