打开、关闭摄像头,谷歌浏览器测试可用.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
video{
width: 50%;
height: 50%;
margin: 50px auto;

display: block;
}
</style>
</head>
<body>

<video id="video"></video>
<script>
var video = document.getElementById('video');


if (navigator.mediaDevices.getUserMedia) {
//最新的标准API
navigator.mediaDevices.getUserMedia({video : {width: 1000, height: 1000}}).then(success).catch(error);
} else if (navigator.webkitGetUserMedia) {
//webkit核心浏览器
navigator.webkitGetUserMedia({video : {width: 1000, height: 1000}},success, error)
} else if (navigator.mozGetUserMedia) {
//firfox浏览器
navigator.mozGetUserMedia({video : {width: 1000, height: 1000}}, success, error);
} else if (navigator.getUserMedia) {
//旧版API
navigator.getUserMedia({video : {width: 1000, height: 1000}}, success, error);
}

function success(stream) {
//兼容webkit核心浏览器
// let CompatibleURL = window.URL || window.webkitURL;

//将视频流设置为video元素的源
console.log(stream);

//video.src = CompatibleURL.createObjectURL(stream);
video.srcObject = stream;
video.play();
}

function error(error) {
console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
}

function test(){
let stream = video.srcObject
console.log(stream);
let tracks = stream.getTracks()
tracks.forEach(track => {
track.stop()
})
video.srcObject = null
}
</script>
<input type="button" onclick="test()" value="close"/>
</body>
</html>

  

posted @ 2020-11-18 10:17  SimpleSmile  阅读(903)  评论(0编辑  收藏  举报