前端页面展示本电脑的摄像头,并使用js获取摄像头列表

可以通过 JavaScript 使用 navigator.mediaDevices.enumerateDevices() 获取电脑上的摄像头列表。以下是一个示例代码,可以展示摄像头列表并选择进行预览。

HTML + JavaScript 实现摄像头列表展示和预览

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>摄像头列表</title>
</head>
<body>
    <h1>摄像头选择</h1>
    <select id="cameraSelect"></select>
    <button onclick="startCamera()">开始预览</button>
    <video id="videoPreview" autoplay playsinline style="width: 100%; max-width: 600px;"></video>

    <script>
        const videoElement = document.getElementById('videoPreview');
        const selectElement = document.getElementById('cameraSelect');

        // 获取摄像头设备列表
        async function getCameraDevices() {
            const devices = await navigator.mediaDevices.enumerateDevices();
            const videoDevices = devices.filter(device => device.kind === 'videoinput');
            
            selectElement.innerHTML = '';  // 清空下拉框

            videoDevices.forEach((device, index) => {
                const option = document.createElement('option');
                option.value = device.deviceId;
                option.text = device.label || `摄像头 ${index + 1}`;
                selectElement.appendChild(option);
            });
        }

        // 启动摄像头
        async function startCamera() {
            const selectedDeviceId = selectElement.value;
            const constraints = {
                video: {
                    deviceId: selectedDeviceId ? { exact: selectedDeviceId } : undefined
                }
            };

            const stream = await navigator.mediaDevices.getUserMedia(constraints);
            videoElement.srcObject = stream;
        }

        // 页面加载时自动获取摄像头
        window.onload = getCameraDevices;
    </script>
</body>
</html>

说明

  • 核心方法 :
    • navigator.mediaDevices.enumerateDevices():列出所有音视频设备。
    • 过滤出 videoinput 类型的设备即为摄像头。
  • 下拉框动态生成 :遍历摄像头设备,将其添加到 <select> 下拉框中。
  • 设备启动 :调用 navigator.mediaDevices.getUserMedia(),使用选定摄像头进行视频预览。这个时候会提示访问权限,要点击允许就可以了

注意事项

  1. 浏览器权限:首次访问页面时,浏览器会请求访问摄像头权限。用户拒绝后,设备列表可能为空。
  2. HTTPS要求getUserMedia 只能在 HTTPS 或 localhost 上使用。
  3. 标签问题:某些设备的标签只有在用户授权访问后才能显示。

运行后,你的页面会自动检测并展示摄像头设备列表,选择设备并点击"开始预览"即可看到实时摄像头画面。但是获取到的本机摄像头没有label标签,不确定外接摄像头是否有标签。

相关推荐
胡耀超15 分钟前
Web Crawling 网络爬虫全景:技术体系、反爬对抗与全链路成本分析
前端·爬虫·python·网络爬虫·数据采集·逆向工程·反爬虫
阿明的小蝴蝶19 分钟前
记一次Gradle环境的编译问题与解决
android·前端·gradle
Ruihong20 分钟前
【VuReact】轻松实现 Vue 到 React 路由适配
前端·react.js
山_雨21 分钟前
startViewTransition
前端
写代码的【黑咖啡】25 分钟前
Python Web 开发新宠:FastAPI 全面指南
前端·python·fastapi
凉_橙25 分钟前
gitlab CICD
前端
wangfpp26 分钟前
性能优化,请先停手:为什么我劝你别上来就搞优化?
前端·javascript·面试
踩着两条虫29 分钟前
AI 驱动的 Vue3 应用开发平台 深入探究(二十):CLI与工具链之构建配置与Vite集成
前端·vue.js·ai编程
凉_橙30 分钟前
前端项目与node项目部署记录
前端
踩着两条虫34 分钟前
AI 驱动的 Vue3 应用开发平台 深入探究(二十):CLI与工具链之自定义构建插件
前端·vue.js·ai编程