前言
现在移动端都很普遍用到生成二维码,一般都是由前端生成,当然也有后台生成返图片给你。
比如生成海报,邀请二维码都有用到。我在项目中遇到的问题就是华为手机长按识别二维码会无法识别,原因大家应该也有搜百度,是应为qrcodejs生成二码后会把canvas display:none但是在华为手机不生效,微信不支持canvas长按识别,我解决的方法就是手动把canvas转图片,隐藏掉自带的那块。直接上代码。
项目用的是VUE,封装的Qrcode的组件
qrCode.vue
<template>
<div class="qrcode_box">
<div ref="code" v-if="!imgData"></div>
<img class="toHtml" :src="imgData" alt v-else />
<slot></slot>
</div>
</template>
<script>
import QRCode from "qrcodejs2";
import html2canvas from "@/libs/html2canvas";
export default {
name: "qrcode",
props: ["text", "type", "color"],
data() {
return {
imgData: ""
};
},
watch: {
text() {
this.codeInit();
},
color() {
this.codeInit();
}
},
mounted() {
this.codeInit();
},
methods: {
codeInit() {
if (!this.$refs.code) return;
this.$refs.code.innerHTML = "";
let w = this.$el.clientWidth,
h = this.$el.clientHeight;
console.log(this.text);
new QRCode(this.$refs.code, {
text: this.text,
width: w,
height: h,
scrollY: 0,
scrollX: 0,
colorDark: this.color || "#000",
colorLight: "#fff",
correctLevel: QRCode.CorrectLevel.L
});
console.log(this.$refs.code);
var canvas=document.getElementsByTagName('canvas')[0];
this.imgData = this.convertCanvasToImage(canvas);
},
convertCanvasToImage(canvas) {
var url = canvas.toDataURL("image/png");
return url;
},
createPicture(w, h) {
console.log("refresh");
// this.$nextTick(() => {
// setTimeout(() => {
// html2canvas(this.$refs.code, {
// backgroundColor: "#fff",
// width: w,
// height: h,
// useOverflow: true,
// useCORS: true
// }).then(canvas => {
// var imgData = canvas.toDataURL("image/jpeg");
// this.imgData = imgData;
// });
// }, 500);
// });
}
}
};
</script>
html2canvas可以不用引用,之前想的是把生成出来的canvas再截一次屏,但是有些手机会只截一般或者黑屏
使用方法
使用的页面
xx.vue
<qr-code class="pop_qrc" :text="shortLink"></qr-code>
import qrCode from "@/components/qrCode";
...此处省略部分代码
components: {
qrCode,
},
.pop_qrc{
width:100px;
height:100px
}
必须要给容器高度宽度,不然会显示不出来