首先呢我們要,安裝一下依賴;
npm install html2canvas --save
接下來我們就直接上代碼了
<van-tab title="簽到二維碼">
<div class="QRCode-box">
<!-- /static/images/QRCode-box.png -->
<van-image src="/static/images/QRCode-box.png" />
<van-image id="imageWrapper" class="QRCode" src="/static/images/QRCode-box.png" />
<van-button color="#29c37f" type="info" @click="toSave">保存二維碼到手機</van-button>
</div>
</van-tab>
// 點擊保存
toSave () {
html2canvas(document.getElementById("imageWrapper")).then(canvas => {
let saveUrl = canvas.toDataURL('image/png')
let aLink = document.createElement('a')
let blob = this.base64ToBlob(saveUrl)
let evt = document.createEvent('HTMLEvents')
evt.initEvent('click', true, true)
aLink.download = '二維碼.jpg'
aLink.href = URL.createObjectURL(blob)
aLink.click()
console.log(aLink.href)
if (aLink.href) {
Toast.success('保存成功')
}
})
},
// 這裏把圖片轉base64
base64ToBlob (code) {
let parts = code.split(';base64,')
let contentType = parts[0].split(':')[1]
let raw = window.atob(parts[1])
let rawLength = raw.length
let uInt8Array = new Uint8Array(rawLength)
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i)
}
return new Blob([uInt8Array], { type: contentType })
},
}
以上vue就可以實現保存圖片到本地了
喜歡上方小程序,需要源碼的,私信小編留下郵箱。