首页 > 建站教程 > 前端框架 >  uni-app将canvas生成的二维码保存到本地正文

uni-app将canvas生成的二维码保存到本地

将之前介绍的uni-app canvas生成二维码下载保存的方法如下,亲测可行:

function saveQrcode() {
    uni.canvasToTempFilePath({
        width: uni.upx2px(400),
        height: uni.upx2px(400),
        canvasId: 'qrcode',
        success: (res) => {
            // #ifndef H5
            uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success(res) {
                    uni.$app.showToast('保存成功')
                },
                fail(err) {
                    uni.$app.showToast('保存失败')
                    console.log('err', err)
                }
            })
            // #endif
            // #ifdef H5
            var arr = res.tempFilePath.split(',')
            var bytes = atob(arr[1])
            let ab = new ArrayBuffer(bytes.length)
            let ia = new Uint8Array(ab)
            for (let i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i)
            }
            var blob = new Blob([ab], {
                type: 'application/octet-stream'
            })
            var url = URL.createObjectURL(blob)
            var a = document.createElement('a')
            a.href = url
            a.download = new Date().valueOf() + ".png"
            var e = document.createEvent('MouseEvents')
            e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
            a.dispatchEvent(e)
            URL.revokeObjectURL(url)
            // #endif
        },
        fail: (res) => {
            uni.$app.showToast('保存失败')
            console.log(res)
        }
    })
}