JavaScript打开摄像头

本文介绍了一个简单的HTML页面,该页面利用JavaScript实现摄像头设备的检测、选择和打开功能。通过调用navigator.mediaDevices API,可以获取并显示可用的摄像头设备,允许用户选择并启动选定的摄像头,同时提供了调整视频尺寸以适应不同屏幕比例的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>一、</title>
</head>
<body>
<video id="video" playsinline=""></video>
<input type="button" class="layui-btn layui-btn-primary" value="打开摄像头" id="openCamera"/>
<select class="select" id="videoDevice"></select>
<script src="camera.js" type="text/javascript"></script>
<script type="text/javascript">
 const ca = new Camera();
 const videoSetting = {width: 480, height: 360};
 const video = document.querySelector('#video');
 const videoDevice = document.querySelector('#videoDevice');
 ca.listCamera(videoDevice).then(() => {
        openCamera(video, videoDevice.value, videoSetting);
 videoDevice.onchange = () => {
            openCamera(video, videoDevice.value, videoSetting);
 };
 document.querySelector('#openCamera').style.display = 'none';
 }).catch((err) => {
        console.log(err);
 console.log('没有可使用的视频设备');
 });
 const openCamera = (video, deviceId, videoSetting) => {
        ca.openCamera(video, deviceId, videoSetting)
            .then((msg) => {
                // 打开摄像头成功
                // 将视频铺满全屏(简单处理)
 let videoWidth = video.offsetWidth;
 let videoHeight = video.offsetHeight;
 if (window.innerWidth < window.innerHeight) {
                    // 竖屏
 if (videoHeight < window.innerHeight) {
                        video.setAttribute('height', window.innerHeight.toString() + 'px');
 }

                } else {
                    // 横屏
 if (videoWidth < window.innerWidth) {
                        video.setAttribute('width', window.innerWidth.toString() + 'px');
 }

                }

            })
            .catch((err) => {
                alert('打开视频设备失败');
 });
 };

</script>
</body>
</html>
camera.js
/**
 * 简单类
 * 关于检测相机,打开相机
 * 2020 0320
 *es6
 */
const Camera = function () {
    var videoDeviceElement = null;
    var videoElement = null;
    var videoSetting = {width: 320, height: 240};
    var canvasElement = null;
    var canvasContext = null;
    /**
     * 列出所有摄像头
     * @param videoDevice
     * @returns {Promise}
     */
    this.listCamera = function(videoDevice) {
        videoDeviceElement = videoDevice;
        return new Promise((resolve, reject) => {
            navigator.mediaDevices.enumerateDevices()
                .then((devices) => {
                    devices.find((device) => {
                        if (device.kind === 'videoinput') {
                            const option = document.createElement('option');
                            option.text = device.label || 'camera '+ (videoDeviceElement.length + 1).toString();
                            option.value = device.deviceId;
                            // 将摄像头id存储在select元素中,方便切换前、后置摄像头
                            videoDeviceElement.appendChild(option);
                        }
                    });
                    if (videoDeviceElement.length === 0) {
                        reject('没有摄像头');
                    } else {
                        videoDeviceElement.style.display = 'inline-block';
                        // 创建canvas,截取摄像头图片时使用
                        // canvasElement = document.createElement('canvas');
                        // canvasContext = canvasElement.getContext('2d');
                        resolve(true);

                    }

                })
                .catch((err) => {
                    reject(err);
                });
        });
    };
    /**
     * 打开摄像头
     * @param video
     * @param deviceId
     * @param setting
     * @returns {Promise}
     */
    this.openCamera = function(video, deviceId, setting) {
        videoElement = video;
        if (setting) {
            videoSetting = setting;
        }
        // 摄像头参数
        // 更多参数请查看 https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamConstraints
        const constraints = {
            audio: false,
            video: {deviceId: {exact: deviceId}}

        };
        // 如果是切换摄像头,则需要先关闭。
        if (videoElement.srcObject) {
            videoElement.srcObject.getTracks().forEach((track) => {
                track.stop();
            });
        }
        return new Promise((resolve, reject) => {
            navigator.mediaDevices.getUserMedia(constraints)
                .then((stream) => {
                    videoElement.srcObject = stream;
                    videoElement.style.display = 'block';
                    videoElement.onloadedmetadata = function(){
                        resolve(true);
                    };
                    videoElement.play();
                })
                .catch((err) => {
                    reject(err);
                });
        });
    };

};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值