插件vue-qr npm install vue-qr --save
<template>
<div class="scan">
<vue-qr ref="Qrcode" :margin='10' :style="scanObj.style" :text="scanObj.url" :size="scanObj.size"></vue-qr>
<canvas id="canvas" ref="canvas" :width="width" :height="height"></canvas>
<div class="button" v-show="scanObj.isShowButton">
<p @click="downScan"><i class="icon"></i><span>较大以上风险二维码</span></p>
</div>
</div>
</template>
<script>
import vueQr from 'vue-qr'
export default {
props:{
scanObj:{
type: Object,
default: {
url:'',
size:80,
style:{},
isShowButton: false,
},
required: false,
},
// canvas width
width: {
type: Number,
default: 400
},
// canvas height
height: {
type: Number,
default: 460
},
// 二维码尺寸(正方形 长宽相同)
qrSize: {
type: Number,
default: 320
},
// 二维码底部文字
qrText: {
type: String,
default: "较大以上风险二维码"
},
//底部说明文字字号
qrTextSize: {
type: Number,
default: 24
}
},
components:{
vueQr
},
data() {
return {
src:''
}
},
mounted() {
},
methods: {
async downScan(){
const iconUrl = this.$refs.Qrcode.$el.src;
let dom = this.$refs['canvas'];
if(dom){
this.handleQrcode(dom,iconUrl)
}
},
handleQrcode(canvas,iconUrl) {
let dom = canvas;
// 画二维码里的logo// 在canvas里进行拼接
const ctx = dom.getContext("2d");
const image = new Image();
image.src = iconUrl;
new Promise((resolve) => {
image.onload = () => {
resolve(image);
};
}).then((img) => {
// console.log(img, ctx)
ctx.drawImage(img, (this.width - this.qrSize) / 2, 0, this.qrSize, this.qrSize);
if (this.qrText) {
//设置字体
ctx.font = "bold " + this.qrTextSize + "px Arial";
let tw = ctx.measureText(this.qrText).width; // 文字真实宽度
let ftop = (this.qrSize - this.qrTextSize) + 30; // 根据字体大小计算文字top
let fleft = (this.width - tw) / 2; // 根据字体大小计算文字left
ctx.fillStyle = "#fff";
ctx.textBaseline = "top"; //设置绘制文本时的文本基线。
ctx.fillStyle = "#333";
ctx.fillText(this.qrText, fleft, ftop);
this.$nextTick(()=>{
let a = document.createElement("a");
//将二维码面板处理为图片
a.href = dom.toDataURL("image/png", 0.5);
a.download = this.qrText + ".png";
a.click();
})
}
});
}
},
}
</script>
<style lang="less" scoped>
@urlTwo: '~@/assets/img/enterprise/details';
.scan{
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
.button{
width: 100%;
display: flex;
align-items: center;
justify-content: center;
p{
display: flex;
align-items: center;
justify-content: center;
font-size: 16px;
line-height: 32px;
padding-top: 10px;
.icon{ // 对应下载图标
display: inline-block;
width: 14px;
height: 15px;
margin-right: 10px;
background: url("@{urlTwo}/icon-down.png") no-repeat center center;
background-size: 100% 100%;
}
span{
font-size: 16px;
color: #086cd2;
font-family: "Microsoft Ya Hei";
cursor: pointer;
}
}
}
#canvas{
position: absolute;
top: 0;
left: 0;
visibility: hidden;
}
}
</style>