uniapp使用video组件播放视频截图

uniapp使用video组件播放视频截图

前言

之前写过一篇uniapp播放视频截图(APP可以用,小程序勿进)的文章,利用renderjs实现了对播放视频进行截图。但是h5的video标签支持的播放格式有限,不像uniapp自带的video组件能支持多种格式和协议视频流。今天我们就实现进阶版对uniapp自带的video组件就行视频截图,这里以播放uniapp官方的视频为例,老规矩,先上图镇楼:
在这里插入图片描述

思路

其实还是之前提到的问题,uniapp自带的video组件并没有提供给我们截图的api,但是我们可以利用HTML5+webview截屏绘制API通过指定区域来对video组件画面截取。

实现

这里不废话,直接上代码了

<template>
	<view>
		<video :src="url"
			   autoplay
			   id="myVideo"
			   style="width: 100%;height: 400rpx;"/>
		<button @click="doshot">截图</button>
		<image :src="shot"
			   style="width: 100%;height: 400rpx;"/>
	</view>
</template>

<script>
	export default {
    
    
		data() {
    
    
			return {
    
    
				url: 'https://img.cdn.aliyun.dcloud.net.cn/guide/uniapp/%E7%AC%AC1%E8%AE%B2%EF%BC%88uni-app%E4%BA%A7%E5%93%81%E4%BB%8B%E7%BB%8D%EF%BC%89-%20DCloud%E5%AE%98%E6%96%B9%E8%A7%86%E9%A2%91%E6%95%99%E7%A8%[email protected]',
				shot: ''
			}
		},
		methods: {
    
    
			doshot(){
    
    
				this.videoContext = uni.createVideoContext('myVideo');//创建视频实例指向video
				this.videoContext.pause();
				this.$nextTick(()=>{
    
    
					this.getCapture()
				})
			},
			getCapture(){
    
    
				let pages = getCurrentPages();  
				let page = pages[pages.length - 1];  
				let ws = page.$getAppWebview()
				var bitmap = new plus.nativeObj.Bitmap('test');  
				// 将webview内容绘制到Bitmap对象中  
				ws.draw(bitmap,()=>{
    
      
				    console.log('截屏绘制图片成功');  
				    // 将原生Bitmap转换成Base64字符串  
					this.shot = bitmap.toBase64Data()
					this.videoContext = uni.createVideoContext('myVideo');//创建视频实例指向video
					this.videoContext.play();
				},(e)=>{
    
      
				    console.log('截屏绘制图片失败:',e);  
				},{
    
    
					check:true,	// 设置为检测白屏
					clip:{
    
    top:uni.getSystemInfoSync().statusBarHeight+45,left:'0px',height:'266px',width:'100%'}	// 设置截屏区域
				}); 
			}
		}
	}
</script>

<style>

</style>

这里需要注意的是,截图之前先停止播放,不停止播放会黑屏,然后截图完成再继续播放。draw函数通过指定clip来控制绘制webview的范围。代码相对来说比上次简单了很多,到这里对video组件截图就完成了,而且支持的格式相比上次更多了,截图更清晰。

尾巴

今天的内容相对来说比较简单,但是能切实解决video组件不能截图的痛点,希望uniapp官方能早点加上video截图的API。如果你喜欢我的文章,欢迎给我点赞,评论,关注,谢谢大家!

猜你喜欢

转载自blog.csdn.net/abs625/article/details/129713542
今日推荐