需求介绍
需求是在uniapp里 对webview组件里的网页进行长截图,获取图片传给后端进行ocr识别
代码部分
1.要获取到展示网页的webview的实例,再用setStyle设置你想要截图的长度,在使用draw实现长截图。
<!-- 外链,webview -->
<template>
<view>
<web-view :src="webviewPath" class="webview"></web-view>
<cover-view class="btn" @click="captureWebview" >截图</cover-view>
</view>
</template>
<script>
export default {
data() {
return {
webviewPath: '',
ws: null,
bitmap: null,
image: '', //截图
};
},
onLoad(option) {
this.webviewPath = option.webviewPath
},
onReady() {
let _this = this
// 获取当前Webview窗口对象
const ws = plus.webview.currentWebview();
// this.ws = ws
var currentWebview = this.$scope.$getAppWebview()
setTimeout(function() {
let wv = currentWebview.children()[0];
_this.ws = wv
_this.ws.setStyle({
height:1000
})
}, 1000); //如果是页面初始化调用时,需要延时一下
},
methods: {
//上传图片
uploadImge(file) {
const that = this
uni.uploadFile({
url: that.$API_URL + 'index/upload', //仅为示例,非真实的接口地址
filePath: file,
name: 'file',
formData: {
'user': 'test'
},
success: res => {
let data = JSON.parse(res.data)
if (res.statusCode == 200 && data.code == '1') {
// that.msg(data.msg || '上传成功');
that.image = data.data.url;
console.log(that.image)
}
},
})
},
// 截屏绘制
captureWebview() {
let _this = this
console.log('截屏绘制')
this.bitmap = new plus.nativeObj.Bitmap('test');
// 将webview内容绘制到Bitmap对象中
let rand = Math.floor(Math.random() * 10000)
let saveUrl = '_doc/' + rand + 'order.jpg'
_this.ws.draw(_this.bitmap, function() {
_this.bitmap.save(saveUrl, {}, function(i) {
_this.uploadImge(i.target)
console.log('保存图片成功:' + JSON.stringify(i));
})
console.log('截屏绘制图片成功', _this.bitmap);
}, function(e) {
uni.hideLoading()
console.log('截屏绘制图片失败:' + JSON.stringify(e));
});
},
}
};
</script>
<style lang="scss" scoped>
.webview {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 1000px;
}
.btn {
position: fixed;
z-index: 10;
left: 50%;
bottom: 250upx;
background-color: #E70115;
transform: translate(-50%, 0);
font-size: 32upx;
border-radius: 48upx;
box-shadow: 0 2upx 2upx #E70115;
width: 500upx;
// margin: 0 24upx;
height: 78upx;
line-height: 78upx;
text-align: center;
color: #fff;
}
</style>