Vuejs轻松实现把生成二维码的弹窗保存到相册

2024年07月21日 建站教程

1、先安装
npm install html2canvas
2、引入
import html2canvas from 'html2canvas';
3、方法
methods:{
    //保存到相册,注意:QRCodeBox是需要保存的最外围id
    toSave() {
      html2canvas(document.getElementById("QRCodeBox")).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()
      });
    },
    //这里把图片转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})
   },
}
//这个方法小编亲测有效!

本文链接:http://so.lmcjl.com/news/8882/

展开阅读全文
相关内容