• 作者:老汪软件技巧
  • 发表时间:2024-12-31 11:11
  • 浏览量:

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

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

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) => {

摄像头web界面__前端调取摄像头

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>

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

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