要使用npm安装vue-qr
和html2canvas
这两个库
npm install vue-qr html2canvas
完整代码
可以根据实际项目需求调整,改成调用接口展示
<template><div><div ref="qrContainer" class="qr-container"><img class="background-image" :src="bgImageUrl" @load="onImageLoaded" @error="onImageError"><vue-qrref="qrCode"class="qr-code":size="200":correct-level="2":dot-scale="0.5":text="qrText"/><img class="logo" :src="logoUrl"><div ref="textDiv" class="text">{{ text }}</div></div><button @click="downloadImage">下载图片</button></div>
</template><script>
import VueQr from 'vue-qr'
import html2canvas from 'html2canvas'export default {components: {VueQr},data() {return {text: '这里是动态添加的文字',qrText: 'https://blog.csdn.net/miaomiaowins',bgImageUrl: 'https://img30.360buyimg.com/babel/s460x460_jfs/t1/102365/29/52131/177484/670f50b4F2c196f5b/2361ae206127204a.jpg.avif',logoUrl: 'https://img30.360buyimg.com/babel/s460x460_jfs/t1/102365/29/52131/177484/670f50b4F2c196f5b/2361ae206127204a.jpg.avif',isImageLoaded: false}},methods: {onImageLoaded() {this.isImageLoaded = true},onImageError() {console.error('背景图片加载失败,请检查图片 URL 或网络连接。')},downloadImage() {if (!this.isImageLoaded) {console.log('背景图片未加载完成,无法下载。')return}html2canvas(this.$refs.qrContainer, { useCORS: true, logging: true }).then((canvas) => {const link = document.createElement('a')link.href = canvas.toDataURL('image/png')link.download = 'qrcode_with_background.png'document.body.appendChild(link)link.click()document.body.removeChild(link)}).catch((error) => {console.error('html2canvas 转换失败:', error)})}}
}
</script><style scoped>
.qr-container {position: relative;width: 500px;height: 500px;
}.background-image {position: absolute;top: 0;left: 0;width: 100%;height: 100%;object-fit: contain;
}.qr-code {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);
}.logo {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);width: 40px; /* 调整logo的大小 */height: 40px; /* 调整logo的大小 */
}
.text {position: absolute;bottom: 10px;left: 10px;color: rgb(205, 10, 10);}
</style>
运行的结果
如果是表格点击实时生成二维码,需要调要用两次,否则可能下载到上一次生成的二维码
downloadImage(e) {if (!this.isImageLoaded) {console.log('背景图片未加载完成,无法下载。')return}html2canvas(this.$refs.qrContainer, { useCORS: true, logging: true }).then((canvas) => {this.Picturemethod(e)})},Picturemethod(e) {html2canvas(this.$refs.qrContainer, { useCORS: true, logging: true }).then((canvas) => {const link = document.createElement('a')link.href = canvas.toDataURL('image/png')link.download = `${e}.png`document.body.appendChild(link)link.click()document.body.removeChild(link)}).catch((error) => {console.error('html2canvas 转换失败:', error)})}