首先 创建一个二维码的位置 (前端做 后端提供url)
<div id="qrcode" ref="qrcode" class="code" />
引入 qrcodejs2
import QRCode from 'qrcodejs2';
获取url
async getCodeUrl() {
this.getQrCode('https://www.baidu.com/'); // demo
},
获取二维码
// 获取二维码
async getQrCode(url) {
await this.$nextTick();
this.imgUrl = new QRCode(this.$refs.qrcode, {
width: 420,
height: 420,
text: url, // 二维码地址
render: 'table',
colorDark: '#000',
colorLight: '#fff',
correctLevel: QRCode.CorrectLevel.H,
});
},
可以下载二维码
// 下载二维码
downloadCode() {
// 先找到canvas节点下的二维码图片
const myCanvas = document
.getElementById('qrcode')
.getElementsByTagName('canvas');
const img = document
.getElementById('qrcode')
.getElementsByTagName('img');
// 创建一个a节点
const a = document.createElement('a');
// 设置a的href属性将canvas变成png格式
const imgURL = myCanvas[0].toDataURL('image/jpg');
const ua = navigator.userAgent;
if (ua.indexOf('Trident') !== -1 && ua.indexOf('Windows') !== -1) {
// IE内核 并且 windows系统 情况下 才执行;
var bstr = atob(imgURL.split(',')[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
const blob = new Blob([u8arr]);
window.navigator.msSaveOrOpenBlob(blob, '下载' + '.' + 'png');
} else if (ua.indexOf('Firefox') > -1) {
// 火狐兼容下载
const blob = this.base64ToBlob(imgURL); // new Blob([content]);
a.download = '信息码'; // 下载图片名称,如果填内容识别不到,下载为未知文件,所以我这里就不填为空
a.href = URL.createObjectURL(blob);
a.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window,
})
); // 兼容火狐
} else {
// 谷歌兼容下载
img.src = myCanvas[0].toDataURL('image/jpg');
a.href = img.src;
// 设置下载文件的名字
a.download = '信息码';
// 点击
a.click();
}
},
效果图
后端做
printCode(rkid) {
XXXXApi.print(rkid).then((res) => {
const print = this.getObjectURL(res);
window.open(print);
});
},
getObjectURL(file) {
let url = null;
if (window.createObjectURL != undefined) {
// basic
url = window.createObjectURL(file);
} else if (window.webkitURL != undefined) {
// webkit or chrome
try {
url = window.webkitURL.createObjectURL(file);
} catch (error) {}
} else if (window.URL != undefined) {
// mozilla(firefox)
try {
url = window.URL.createObjectURL(file);
} catch (error) {}
}
return url;
},