Files
shanxia2.0/miniprogram/utils/makeQrTempFile.js
T

53 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import UQRCode from 'uqrcodejs'
/**
* 在组件内隐藏 canvas 上绘制二维码,导出临时文件路径供 <image> 展示。
* @param {object} opts
* @param {string} opts.text 二维码内容(出入库单 id)
* @param {string} opts.canvasId canvas-id
* @param {object} opts.componentInstance 组件实例(getCurrentInstance().proxy)
* @param {number} [opts.size=200]
* @returns {Promise<string>} tempFilePath
*/
export function makeQrTempFile({ text, canvasId, componentInstance, size = 200 }) {
const content = String(text || '').trim()
if (!content) {
return Promise.reject(new Error('二维码内容为空'))
}
if (!componentInstance) {
return Promise.reject(new Error('缺少组件实例'))
}
return new Promise((resolve, reject) => {
try {
const qr = new UQRCode()
qr.data = content
qr.size = size
qr.margin = 10
qr.make()
const ctx = uni.createCanvasContext(canvasId, componentInstance)
qr.canvasContext = ctx
qr.drawCanvas()
setTimeout(() => {
uni.canvasToTempFilePath(
{
canvasId,
width: size,
height: size,
destWidth: size,
destHeight: size,
success: (res) => {
if (res.tempFilePath) resolve(res.tempFilePath)
else reject(new Error('二维码导出失败'))
},
fail: (err) => reject(err || new Error('二维码导出失败'))
},
componentInstance
)
}, 120)
} catch (e) {
reject(e)
}
})
}