Vue 实现生成二维码(qrcodejs2),并生成图片(html2canvas)
1 、引包
npm install qrcodejs2 --save
npm install --save html2canvas
import html2canvas from 'html2canvas'
import QRCode from 'qrcodejs2'
2 、生成二维码
tip:需要写一个定宽,不然生成图片会发生偏移和二维码不完整
<div id="qrCode" class="qrconde" ref="qrCodeDiv" v-if="imgData==''" style="width: 200px;height: 200px"></div>
3、生成二维码
提示
调用此方法要使用this.$nextTick(()=>{
this.bindQRCode ()
}),否则报错
bindQRCode () {
new QRCode(this.$refs.qrCodeDiv, {
// text: 'http://192.168.0.xx:8765/#/SignAgency?code=' + t.userInfo.account,
width: 200,
height: 200,
colorDark: '#333333', // 二维码颜色
colorLight: '#ffffff', // 二维码背景色
correctLevel: QRCode.CorrectLevel.L// 容错率,L/M/H
})
},
4、合成成海报图片
提示:若使用再移动端,二维码或者logo尺寸为动态,则把样式宽高等像素改Px,则不会转rem,若pc端和移动端都使用,pc端合成在移动端展示(移动端宽高Px)则会出现白边,so在pc端合成也需使用Px。
注意点:在pc端写width,height.不然pc浏览器缩放为90%会有白边出现偏差
//布局样式自定义
<---根据自己需求可写文字或者图片布局好样式>>>背景图最好不要使用:sbackground:'ur)图片会模糊--->
<div ref="posterSync">
<div class="backImage" >
//背景图
<img :src="backIMg" alt='' class='bgImg'/>
//二维码或者小logo
<div id="qrCode" class="qrconde" ref="qrCodeDiv" style="width:200px;height: 200px"></div>
</div>
</div>
function createPicture () {
html2canvas(this.$refs.posterSync, {
scale:3,//扩大防止字体模糊
}).then(canvas => {
var imgData = canvas.toDataURL('image/jpeg')
})
},
//css
.posterSync{
position:'absolute',
width:'300px';
height:'300px';
}
.backImage{
position:'relative';
width:'300px';
height:'300px';
}
.bgImg{
width:100%;
height:'100%;
}
.qrconde{
position:'relative';
}
将base64转blob
getUrlBlob(url,fileName='file'){
var arr=url.split(",")
var mime =arr[0].match(/:(.*?);/)[1]
const suffix =mime.split("/")[1]
var bstr =atob(arr[1])
var n=bstr.length
var u8arr=new Uint8Array(n)
while(n--){
u8arr[n]=bstr.charCodeAt(n)
}
retrun new File([u8rr],`${fileName}.${suffix},{type:mime}`)
}
标题
new formData=new FormData()
formData.append("file",file)