1. 效果
打开摄像头
关闭摄像头(包括指示灯也关了的)
2. 代码
- open_close_camera.html
// open_close_camera.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>use camera</title>
<link rel="stylesheet" href="css.css">
<script>
"use strict";
// 定义全局变量
let localStream = Object;
let video = Object;
function accessCamera() {
video = document.getElementById("video");
// 创建一个媒体流请求对象
const constraints = {
video: true,
audio: false
};
// 使用 getUserMedia 方法访问摄像头
navigator.mediaDevices.getUserMedia(constraints)
.then(function (stream) {
// 使用这个视频流
localStream = stream;
// 将视频流赋值给 video 元素的 src 属性,以显示摄像头的视频
video.srcObject = localStream;
video.onloadedmetadata = function (e) {
video.play();
};
})
.catch(function (error) {
console.error("访问摄像头失败:", error);
});
}
function closeCamera() {
localStream.getVideoTracks()[0].stop();
localStream.src = '';
}
</script>
</head>
<body>
<h1>use camera</h1>
<video id="video" width="900px" height="600px" autoplay></video>
<button onclick="accessCamera()">open camera</button>
<button onclick="closeCamera()">close camera</button>
</body>
</html>