uniapp 使用webview组件实现长截图

该文章介绍了如何在uniapp中使用webview组件对网页进行长截图,通过设置webview的高度并利用draw方法实现截图,然后保存为Bitmap对象。接着,文章展示了如何将截图保存并上传至服务器,以便进行OCR识别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

uniapp 使用webview组件实现长截图

需求介绍

需求是在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>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

MrHao_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值