<template>
<view class="container">
<video
id="myVideo"
:autoplay="true"
controls
:src="localVideoSrc"
@loadedmetadata.once="initVideo"
class="check-video"
></video>
<canvas type="2d" canvas-id="myCanvas" id="myCanvas" style="width: 1px; height: 1px"></canvas>
</view>
</template>
注意这里给canvas指定2d类型
<script>
export default {
data() {
return {
localVideoSrc: '',
videoInfo: {},
timer: null, //定时器
imageDataList: [], // 视频截取图片地址集
}
},
methods: {
async initVideo(e) {
console.log(e, '视频元数据加载完成时触发')
this.videoInfo = await e.detail
// 开始把视频画面绘制到canvas
this.drawCanvas()
},
// 获取canvas
getCanvasNode(id, instance) {
const query = uni.createSelectorQuery().in(instance)
const queryCvs = query.select(`#${id}`).node()
return new Promise((resolve, reject) => {
queryCvs.exec((res) => {
resolve(res)
})
})
},
// 获取video节点
getVideoContext(id, instance) {
const query = uni.createSelectorQuery().in(instance)
const queryVideo = query.select(`#${id}`).context()
return new Promise((resolve, reject) => {
queryVideo.exec((res) => {
resolve(res)
})
})
},
async drawCanvas() {
const { width, height, duration } = this.videoInfo // 实现获取到的视频的信息
// 测试
// const { width, height, duration } = { width: 560, height: 300, duration: 3 } // 实现获取到的视频的信息
console.log(width, height, duration, '视频信息')
// 获取video元素和canvas元素
const videoRes = await this.getVideoContext('myVideo', this)
const video = videoRes[0].context
const canvasRes = await this.getCanvasNode('myCanvas', this)
const canvas = canvasRes[0].node
// 改变canvas的尺寸
canvas.width = width
canvas.height = height
const ctx = canvas.getContext('2d')
let computedLen = Math.floor(duration) // 计算可截取的数量
try {
this.timer = setInterval(async () => {
if (computedLen < 1) {
clearInterval(this.timer)
console.log('截取完成')
// TODO...
return
}
ctx.drawImage(video, 0, 0, width, height, 0, 0, canvas.width, canvas.height)
// 生成图片
uni.canvasToTempFilePath({
canvas,
success: (res) => {
// 生成的图片临时文件路径
console.log(res.tempFilePath)
this.imageDataList.push(res.tempFilePath)
},
complete: (res) => {
console.log(res, 'complete')
}
})
computedLen--
}, 1000)
} catch (err) {}
}
}
在drawCanvas()里注意这几个地方!,我是定时器1S截取一次video画面,逐帧截取记得换算下
微信小程序文档传送门: wx.canvasToTempFilePath(Object object, Object this)