qrcodejs2生成二维码
需引用qrcodejs2
try {
if (this.qrStyle && this.qrStyle.text) {
if (this.qrCode) {
this.qrCode.clear(); // 清除二维码
this.qrCode.makeCode(this.qrStyle.text); // 生成另外一个二维码
} else {
this.qrCode = new QRCode(this.$refs.qrCodeBox, this.qrStyle);
}
} else {
this.$message.error("二维码生成参数为空");
}
} catch (e) {
console.log(e)
this.$message.error(e)
}
js 保存二维码图片
try {
//找到需要转换的canvas
var data = this.$refs.qrCodeBox.children[0].toDataURL().replace("image/png",
"image/octet-stream;"); //获取二维码值,并修改响应头部。
var filename = `${this.hint||this.qrContent}.png`; //保存的图片名称和格式,canvas默认使用的png格式。这个格式效果最好。
var save_link = document.createElement('a');
save_link.href = data;
save_link.download = filename;
save_link.click()
} catch (e) {
console.log(e)
this.$message.error(e)
}
js 居中打印二维码
利用隐藏的iframe 进行window.print() 可以防止当前页面布局混乱(特别是Vue项目)
var content = this.$refs.printBox.innerHTML;
var iframe = document.createElement('iframe');
var f = document.body.appendChild(iframe);
iframe.id = "myIframe";
iframe.setAttribute('style', "display:table;position:relative;width:0px;height:0px;top:-10px;left:-10px;");
var w = f.contentWindow || f.contentDocument;
var doc = f.contentDocument || f.contentWindow.document;
doc.open();
doc.write(content);
var qrBox = doc.getElementById("qrCodeBox");
var ptStyle = this.printStyle
if (!ptStyle) {
ptStyle =
`display:table-cell;vertical-align:middle;position:absolute;top:50%;left:50%;margin-top:-${this.qrWidth/2};margin-left:-${this.qrHeight/2};`
}
qrBox.setAttribute('style', ptStyle)
var div = doc.getElementById('hint')
var isShowHint = this.isPrintHint && this.hint
div.style.display = isShowHint ? 'inline' : 'none';
doc.close();
w.focus();
w.print();
document.body.removeChild(iframe)
w.close();
} catch (e) {
console.log(e)
this.$message.error(e)
}
body内容
<div ref="printBox" class="code-image">
<div id="qrCodeBox" ref="qrCodeBox"></div>
<div id="hint" class="print-info">{{hint}}</div>
</div>
|