accessing webcam in web pages

前端 未结 2 1875
傲寒
傲寒 2021-01-01 03:05

I am developing a web application.

In my guest registration page I need to access web cam for taking images of guests.

The image which I tak

2条回答
  •  孤城傲影
    2021-01-01 03:19

    Answering own question, as there is a better way using HTML5 is available.

    Option 1, Accessing default camera from the system

    HTML

    Video Tag
    

    Canvas

    Script

    var width = 320;
    var height = 0;
    var streaming = false;
    
    navigator.mediaDevices.getUserMedia({video: true, audio: false})
            .then(function (stream) {
                video.srcObject = stream;
                video.play();
            })
            .catch(function (err) {
                console.log("An error occured! " + err);
            });
    
    video.addEventListener('canplay', function (ev) {
        if (!streaming) {
            height = video.videoHeight / (video.videoWidth / width);
            video.setAttribute('width', width);
            video.setAttribute('height', height);
            canvas.setAttribute('width', width);
            canvas.setAttribute('height', height);
    
            streaming = true;
        }
    }, false);
    
    startbutton.addEventListener('click', function (ev) {
        takepicture();
        ev.preventDefault();
    }, false);
    
    clearphoto();
    
    function clearphoto() {
        var context = canvas.getContext('2d');
        context.fillStyle = "#AAA";
        context.fillRect(0, 0, canvas.width, canvas.height);
    }
    
    function takepicture() {
        var context = canvas.getContext('2d');
        if (width && height) {
            canvas.width = width;
            canvas.height = height;
            context.drawImage(video, 0, 0, width, height);
    
            var dataURL = canvas.toDataURL("image/jpeg", 0.95);
            if (dataURL && dataURL != "data:,") {
                var fileName = generateImageName();
                uploadimage(dataURL, fileName);
            } else {
                alert("Image not available");
            }
        } else {
            clearphoto();
        }
    }
    
    function generateImageName() {
        ... generate image name logic here ...
        return imageName;
    }
    
    function uploadimage(dataurl, filename) {
        ... upload logic here ...
    }
    

    Screen shot

    Option 2, Provide a list of available cameras in the system, and let user select the camera.

    HTML

    
        
        
    Video Tag

    Canvas

    Script

    var width = 320;
    var height = 0;
    var streaming = false;
    var localstream = null;
    
    startCameraButton.onclick = start;
    takePictureButton.onclick = takepicture;
    
    navigator.mediaDevices.enumerateDevices()
            .then(gotDevices)
            .catch(function (err) {
                console.log("An error occured while getting device list! " + err);
            });
    
    function gotDevices(deviceInfos) {
        while (videoSelect.firstChild) {
            videoSelect.removeChild(videoSelect.firstChild);
        }
    
        for (var i = 0; i !== deviceInfos.length; ++i) {
            var deviceInfo = deviceInfos[i];
            var option = document.createElement('option');
            option.value = deviceInfo.deviceId;
            if (deviceInfo.kind === 'videoinput') {
                option.text = deviceInfo.label || 'Camera ' + (videoSelect.length + 1);
                videoSelect.appendChild(option);
            }
        }
    }
    
    function start() {
        stopVideo();
        clearphoto();
        var videoSource = videoSelect.value;
        var constraints = {
            audio: false,
            video: {deviceId: videoSource ? {exact: videoSource} : undefined}
        };
        navigator.mediaDevices.getUserMedia(constraints).
                then(gotStream).then(gotDevices).catch(handleError);
    }
    
    
    
    function gotStream(stream) {
        localstream = stream;
        video.srcObject = stream;
        video.play();
        // Refresh button list in case labels have become available
        return navigator.mediaDevices.enumerateDevices();
    }
    
    function handleError(error) {
        console.log('navigator.getUserMedia error: ', error);
    }
    
    video.addEventListener('canplay', function (ev) {
        if (!streaming) {
            height = video.videoHeight / (video.videoWidth / width);
            video.setAttribute('width', width);
            video.setAttribute('height', height);
            canvas.setAttribute('width', width);
            canvas.setAttribute('height', height);
    
            streaming = true;
        }
    }, false);
    
    clearphoto();
    
    function clearphoto() {
        var context = canvas.getContext('2d');
        context.fillStyle = "#AAA";
        context.fillRect(0, 0, canvas.width, canvas.height);
    }
    
    function takepicture() {
        var context = canvas.getContext('2d');
        if (width && height) {
            canvas.width = width;
            canvas.height = height;
            context.drawImage(video, 0, 0, width, height);
    
            var dataURL = canvas.toDataURL("image/jpeg", 0.95);
            if (dataURL && dataURL != "data:,") {
                var fileName = generateImageName();
                fileName = fileName + ".txt"
                uploadimage(dataURL, fileName);
            } else {
                console.log("Image not available");
            }
        } else {
            clearphoto();
        }
    }
    
        function generateImageName() {
        ... generate image name logic here ...
        return imageName;
    }
    
    function uploadimage(dataurl, filename) {
        ... upload logic here ...
    }
    
    function stopVideo() {
        if (localstream) {
            localstream.getTracks().forEach(function (track) {
                track.stop();
                localstream = null;
            });
        }
    }
    

    Screen Shot

    Option 3, let user select audio and video sources and audio output

    In option 2, user can select any particular camera. On top of that if user want to select audio source and audio output source also, modify the above code with below changes.

    HTML

                audioInputSelect
                

    audioOutputSelect

    Script

    function gotDevices(deviceInfos) {
        while (videoSelect.firstChild) {
            videoSelect.removeChild(videoSelect.firstChild);
        }
    
        for (var i = 0; i !== deviceInfos.length; ++i) {
            var deviceInfo = deviceInfos[i];
            var option = document.createElement('option');
            option.value = deviceInfo.deviceId;
            if (deviceInfo.kind === 'audioinput') {
                option.text = deviceInfo.label || 'Microphone ' + (audioInputSelect.length + 1);
                audioInputSelect.appendChild(option);
            } else if (deviceInfo.kind === 'audiooutput') {
                option.text = deviceInfo.label || 'Speaker ' + (audioOutputSelect.length + 1);
                audioOutputSelect.appendChild(option);
            } else if (deviceInfo.kind === 'videoinput') {
                option.text = deviceInfo.label || 'Camera ' + (videoSelect.length + 1);
                videoSelect.appendChild(option);
            }
        }
    }
    
    function start() {
        stopVideo();
        clearphoto();
        var audioSource = audioInputSelect.value;
        var videoSource = videoSelect.value;
        var constraints = {
          audio: {deviceId: audioSource ? {exact: audioSource} : undefined},
            video: {deviceId: videoSource ? {exact: videoSource} : undefined}
        };
        navigator.mediaDevices.getUserMedia(constraints).
                then(gotStream).then(gotDevices).catch(handleError);
    }
    

提交回复
热议问题