h5调用摄像头加取景框
时间: 2024-01-22 12:02:54 浏览: 170
要实现在H5页面中调用摄像头并添加取景框,可以使用HTML5的`getUserMedia`API和Canvas。具体步骤如下:
1. 使用`getUserMedia`API获取摄像头的视频流:
```javascript
navigator.mediaDevices.getUserMedia({
video: true,
audio: false
}).then(stream => {
const video = document.querySelector('video');
video.srcObject = stream;
video.play();
}).catch(error => {
console.error(error);
});
```
2. 创建一个Canvas元素,并将视频流渲染到Canvas上:
```javascript
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
function render() {
context.drawImage(video, 0, 0, canvas.width, canvas.height);
requestAnimationFrame(render);
}
render();
```
3. 绘制取景框:
```javascript
const boxWidth = 200;
const boxHeight = 200;
const boxX = (canvas.width - boxWidth) / 2;
const boxY = (canvas.height - boxHeight) / 2;
context.strokeStyle = 'red';
context.strokeRect(boxX, boxY, boxWidth, boxHeight);
```
完整代码示例:
```html
<video></video>
<canvas></canvas>
<script>
navigator.mediaDevices.getUserMedia({
video: true,
audio: false
}).then(stream => {
const video = document.querySelector('video');
video.srcObject = stream;
video.play();
const canvas = document.querySelector('canvas');
const context = canvas.getContext('2d');
const boxWidth = 200;
const boxHeight = 200;
const boxX = (canvas.width - boxWidth) / 2;
const boxY = (canvas.height - boxHeight) / 2;
function render() {
context.drawImage(video, 0, 0, canvas.width, canvas.height);
context.strokeStyle = 'red';
context.strokeRect(boxX, boxY, boxWidth, boxHeight);
requestAnimationFrame(render);
}
render();
}).catch(error => {
console.error(error);
});
</script>
```
阅读全文
相关推荐













