uniapp 截屏扫码
最近开发功能遇到个需求,用户点击某个操作之后,需要截取当前屏幕内容,并扫码识别屏幕截图中的二维码,代码如下:
首先将代码抽离到外部文件中,以便复用:
// 截图 export function takeScreenshot() { return new Promise(resolve => { var pages = getCurrentPages() //获取当前页面信息 var page = pages[pages.length - 1] var bitmap = null var currentWebview = page.$getAppWebview() bitmap = new plus.nativeObj.Bitmap('amway_img') // 将webview内容绘制到Bitmap对象中 currentWebview.draw(bitmap, function() { // console.log('截屏绘制图片成功'); let rand = Math.floor(Math.random() * 10000) let saveUrl = '_doc/' + rand + 'a.jpg' // resolve(saveUrl) bitmap.save(saveUrl, {}, function(i) { resolve(i.target) }, function(e) { resolve(false) console.log('保存图片失败:' + JSON.stringify(e)) }) }, function(e) { resolve(false) console.log('截屏绘制图片失败:' + JSON.stringify(e)) }) }) } // 扫描本地二维码 export function scanLocalImgCode(url) { return new Promise(resolve => { uni.getImageInfo({ src: url, success: function(image) { plus.barcode.scan(image.path, function(type, result) { resolve(result) console.log('扫描成功:(' + type + ')' + result) }, function(e) { resolve(false) console.log('扫描失败: ' + JSON.stringify(e)) }) } }) }) }
页面中使用
// 扫码 async handleScan() { const imgPath = await takeScreenshot() if (imgPath) { const codeContent = await scanLocalImgCode(imgPath) if (codeContent) { console.log(codeContent); } else { this.$toast('扫码失败,请确保二维码在屏幕中完整显示哦', 2000) } } },