How js calls the computer's camera

Posted by optik on Tue, 31 Mar 2020 13:29:55 +0200

Nothing to do, write a demo calling the camera with js, and save it with canvas display. This function is very practical, such as uploading the user's Avatar, taking photos in real time and uploading in time.

Html:

  <video width="200px" height="150px"></video>
    <canvas width="200px" height="150px"></canvas>
    <p>
        <button id="start">Turn on the camera</button>
        <button id="snap">Intercept images</button>
        <button id="close">Turn off camera</button>
    </p>

JavaScript:

 window.onload = function () {
            var canvas = document.getElementsByTagName('canvas')[0],
                context = canvas.getContext('2d'),
                video = document.getElementsByTagName("video")[0],
                snap = document.getElementById("snap"),
                close = document.getElementById("close"),
                start = document.getElementById("start"),
                MediaStreamTrack;
            start.addEventListener('click', function () {
                if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                    navigator.mediaDevices.getUserMedia({
                        video: true,
                        audio: true
                    }).then(function (stream) {
                        console.log(stream);
                        MediaStreamTrack=typeof stream.stop==='function'?stream:stream.getTracks()[1];
                        video.src=(window.URL).createObjectURL(stream);
                        video.play();
                    }).catch(function(err){
                        console.log(err);
                    });
                }else if(navigator.getMedia){
                    navigator.getMedia({
                        video: true
                    }).then(function (stream) {
                        console.log(stream);
                        MediaStreamTrack=stream.getTracks()[1];
                        video.src=(window.webkitURL).createObjectURL(stream);
                        video.play();
                    }).catch(function(err){
                        console.log(err);
                    });
                }
            });
            snap.addEventListener('click', function () {
                context.drawImage(video, 0, 0,200,150);
            });
            close.addEventListener('click', function () {
                MediaStreamTrack && MediaStreamTrack.stop();
            });
        }

Summary: the Demo above mainly uses the camera component of the browser, and then assigns the image source to canvas. One of them encountered a pit: the code needs to be hosted on the server side, that is, it needs to be accessed on the client side to call the browser successfully. This prohibition of local calls may be due to the security of the browser and the privacy of the user.

Topics: Javascript