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>