给我一个 vue 在视频流上画出感兴趣区域的代码
时间: 2024-03-24 13:36:26 浏览: 15
好的,下面是一个基于 Vue 和 HTML5 的 Canvas API 实现在视频流上画出感兴趣区域的示例代码。
首先,我们需要用 `getUserMedia()` 方法获取视频流,并将其绑定到 `<video>` 元素上。接着,我们创建一个 `<canvas>` 元素用来画出感兴趣区域,然后在 `<video>` 元素上监听 `play` 事件,每次视频播放时都会触发 `draw()` 方法,我们可以在这个方法里面读取视频帧,并在 `<canvas>` 上画出感兴趣区域。
以下是示例代码:
```html
<template>
<div>
<video ref="video" autoplay></video>
<canvas ref="canvas"></canvas>
</div>
</template>
<script>
export default {
mounted() {
this.video = this.$refs.video;
this.canvas = this.$refs.canvas;
this.ctx = this.canvas.getContext('2d');
navigator.mediaDevices.getUserMedia({video: true})
.then(stream => {
this.video.srcObject = stream;
this.video.play();
this.draw();
})
.catch(error => {
console.error('getUserMedia error:', error);
});
},
methods: {
draw() {
const w = this.video.videoWidth;
const h = this.video.videoHeight;
this.canvas.width = w;
this.canvas.height = h;
this.ctx.drawImage(this.video, 0, 0, w, h);
this.ctx.strokeStyle = '#ff0000';
this.ctx.strokeRect(w / 4, h / 4, w / 2, h / 2); // 画出感兴趣区域
requestAnimationFrame(() => {
this.draw();
});
}
}
}
</script>
```
在上面的代码中,我们在 `draw()` 方法中使用 `requestAnimationFrame()` 方法来循环调用自身,以便在每个视频帧上更新 `<canvas>` 元素。在 `strokeRect()` 方法中,我们画出了一个宽度为视频宽度的矩形,高度为视频高度的一半,位于视频中心。你可以根据自己的需求调整矩形的大小和位置。
希望这个示例对你有所帮助。如果你还有其他问题,欢迎随时问我。