安裝
npm install html2canvas --save
npm install qrcodejs2 --save //二維碼
引入
import html2canvas from 'html2canvas'
import QRCode from 'qrcodejs2';
生成二維碼
<div id="qrCode" ref="qrCodeDiv" v-if="isDom"></div>
qrCode() {
new QRCode(this.$refs.qrCodeDiv, { //this.$refs.qrCodeDiv生成二維碼的dom
text: xxx, //二維碼地址
width: 125,
height: 125,
colorDark: "#333333", //二維碼顏色
colorLight: "#ffffff", //二維碼背景色
correctLevel: QRCode.CorrectLevel.L//容錯(cuò)率,L/M/H
})
},
把生成的二維碼和海報(bào)圖樣式寫好之后就用html2canvas生成圖片
// 畫圖區(qū)域
<div class="share" id="html2canvas" ref="html2canvas">
<img :src="ewm" alt="" v-if="isDom" >
<div id="qrCode" ref="qrCodeDiv" v-if="isDom"></div>
</div>
shareImage() {
var targetDom = this.$refs.html2canvas //畫圖區(qū)域的dom
html2canvas(targetDom, {
allowTaint: false,
useCORS: true,
height: targetDom.offsetHeight,
width: targetDom.offsetWidth,
taintTest: true, // 在渲染前測試圖片
timeout: 500, // 加載延時(shí)
windowWidth: document.body.scrollWidth,
windowHeight: document.body.scrollHeight,
dpi: window.devicePixelRatio * 2,
scale: 2
// backgroundColor: 'rgb(213,201,221)'
}).then(canvas => {
this.$refs.html2canvas.append(canvas);//在下面添加canvas節(jié)點(diǎn)
this.isDom = false
let link = document.createElement("a");
link.href = canvas.toDataURL();//下載鏈接
link.setAttribute("download","體檢表.png");
link.style.display = "none";//a標(biāo)簽隱藏
document.body.appendChild(link);
// link.click(); // 直接觸發(fā)下載事件 看需求是否需要
})
},
mouted() {
getCode() {
this.isDom = true
/** f (this.$refs.html2canvas) {
this.$refs.html2canvas.removeChild(this.$refs.html2canvas.lastChild)
}
防止每次重復(fù)生成二維碼*/
this.$nextTick(() => {
this.qrCode()
setTimeout(() => {
this.shareImage() //生成的時(shí)候需要放在定時(shí)器里面 防止生成的海報(bào)畫圖有偏差,如果有白邊可以嘗試把定時(shí)器的時(shí)間延長
}, 200)
})
},
}