后台项目二维码导出并下载功能
vue导出二维码并下载功能
qrcodejs2:qrcodejs2
UI:element
html2canvas:html2canvas
效果图
安装
npm install qrcodejs2 --save
npm install html2canvas --save
引入
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
HTML
<el-dialog title="查看分享链接" :visible.sync="getlinkVisible" width="400px" @close="closeCode">
<div style="text-align: center; width: 100%">
<div id="qrcode" ref="qrcode" class="qrcode"></div>
</div>
<span slot="footer" class="dialog-footer">
<el-button type="primary" @click="saveQrCode">下载</el-button>
<el-button @click="getlinkVisible = false">取 消</el-button>
</span>
</el-dialog>
CSS
我使用的是less
用于设置二维码的边框
.qrcode {
display: inline-block;
padding: 6px;
border: 2px solid black;
img {
width: 132px;
height: 132px;
background-color: #fff; //设置白色背景色
padding: 6px; // 利用padding的特性,挤出白边
box-sizing: border-box;
}
}
JS
生成二维码
qrcode(h5Link) {
this.qr = new QRCode('qrcode', {
text: window.location.protocol+window.location.host+'/GradePhone?h5Link='+h5Link,
width: 128,
height: 128,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H,
})
console.log(this);
},
导出图片
saveQrCode() {
html2canvas(this.$refs.qrcode).then(function (canvas) {
let link = document.createElement('a')
link.href = canvas.toDataURL() //下载链接
link.setAttribute('download', '二维码.png')
link.style.display = 'none' //a标签隐藏
document.body.appendChild(link)
link.click()
})
},