手机H5自动显示相机画面,并实现前后摄像头切换

1. 页面加载自动获取摄像头流显示预览
2. 提供按钮切换前后摄像头
3. 通过设备ID来切换指定摄像头

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<!DOCTYPE html>
<html>
<head>
  <!-- 设置页面编码和标题 -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Camera App</title>
  <!-- 一些页面样式 -->
  <style>
    #camera { width: 100%; height: 500px; object-fit: cover; }
    button { font-size: 16px; padding: 8px 16px; }
  </style>
 
</head>
<body>
  <!-- 显示摄像头预览的video元素 -->
  <video id="camera" autoplay playsinline></video>  
  <!-- 按钮来切换前后摄像头 -->
  <button id="switch">Switch Camera</button>
  <script>
    // 获取页面元素
    const cameraView = document.getElementById('camera');
    const switchButton = document.getElementById('switch');
    // 当前使用的设备id
    let currentDeviceId;
    // 获取摄像头流的方法 
    async function getCameraStream() {
      // 获取所有媒体设备
      const devices = await navigator.mediaDevices.enumerateDevices(); 
      // 过滤出视频输入设备(摄像头)
      const videoDevices = devices.filter(device => device.kind === 'videoinput');
      // 默认使用第一个视频设备
      currentDeviceId = videoDevices[0].deviceId;
 
      // 获取这个设备的流 
      const stream = await navigator.mediaDevices.getUserMedia({
        video: {
          deviceId: currentDeviceId
        }
      });
      // 绑定流到video元素  
      cameraView.srcObject = stream;
    }
 
    // 切换摄像头的方法
    async function switchCamera() {
      // 再次获取媒体设备列表
      const devices = await navigator.mediaDevices.enumerateDevices();
      // 过滤出视频输入设备
      const videoDevices = devices.filter(device => device.kind === 'videoinput');
      // 找到第一个与当前不同的设备
      for (const device of videoDevices) {
        if (device.deviceId !== currentDeviceId) {
          currentDeviceId = device.deviceId; 
          break;
        }
      }
      // 获取这个设备的新流
      const stream = await navigator.mediaDevices.getUserMedia({
        video: {
          deviceId: currentDeviceId
        }
      });
      // 绑定新流到video元素  
      cameraView.srcObject = stream;
    }
    // 页面加载时获取流
    getCameraStream();
    // 点击按钮切换摄像头
    switchButton.addEventListener('click', switchCamera);
  </script>
</body>
</html>

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注