网页调用电脑摄像头,可以自动添加摄像头的个数,我这里只有添加了两个摄像头,可以根据自己的需要添加。
<!doctype html>
<html lang="en">
<head>
<title>GET VIDEO</title>
<meta charset="utf-8">
<style>
.video_con {
float: left;
width: 48%;
height: 31%;
background-color: #666;
margin-left: 1%;
margin-top: 0.5%;
}
.video {
float: right;
width: 48%;
height: 31%;
background-color: #666;
margin-left: 1%;
margin-top: 0.5%;
}
</style>
</head>
<body onload="getMedia(),getMedia1()">
<div class="video_con">
<!-- <button id="snap" οnclick="takePhoto()">拍照</button>-->
<!-- <input type="button" title="开启摄像头" value="开启摄像头" οnclick="getMedia()" />-->
<video id="video" controls preload="none" width="100%" height="100%" data-setup="{}" autoplay="autoplay"> </video>
</div>
<div class="video">
<video id="video1" controls preload="none" width="100%" height="100%" data-setup="{}" autoplay="autoplay"> </video>
</div>
<!--<video id="video" width="500px" height="500px" autoplay="autoplay"></video>-->
<canvas id="canvas" width="500px" height="500px"></canvas>
<script>
function getMedia() {
let constraints = {
video: {width: 600, height: 300},
audio: true
};
//获得video摄像头区域
let video = document.getElementById("video");
//这里介绍新的方法,返回一个 Promise对象
// 这个Promise对象返回成功后的回调函数带一个 MediaStream 对象作为其参数
// then()是Promise对象里的方法
// then()方法是异步执行,当then()前的方法执行完后再执行then()内部的程序
// 避免数据没有获取到
let promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then(function (MediaStream) {
video.srcObject = MediaStream;
video.play();
});
}
function getMedia1() {
let constraints = {
video: {width: 600, height: 300},
audio: true
};
//获得video摄像头区域
let video1 = document.getElementById("video1");
//这里介绍新的方法,返回一个 Promise对象
// 这个Promise对象返回成功后的回调函数带一个 MediaStream 对象作为其参数
// then()是Promise对象里的方法
// then()方法是异步执行,当then()前的方法执行完后再执行then()内部的程序
// 避免数据没有获取到
let promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then(function (MediaStream) {
video1.srcObject = MediaStream;
video1.play();
});
}
// function takePhoto() {
// //获得Canvas对象
// let video = document.getElementById("video");
// let canvas = document.getElementById("canvas");
// let ctx = canvas.getContext('2d');
// ctx.drawImage(video, 0, 0, 500, 500);
// }
// setTimeout("getMedia()",3000); 设置定时器自动调用方法
</script>
</body>
</html>
实时效果图