Search code examples
javascriptgetusermedia

How can I detect width and height of the webcamera?


How can I detect width and height of the camera to use it on canvas and maintain the proportions??

I need to detect width and height of the camera and then use it on a canvas. In the new canvas I will show the live video with some filters. The size of the camera should be the same as the video.

The code I use to get access to the camera:

navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || naviagor.msGetUserMedia);

    var options = {video: true};
    var videoWidth, videoHeight;

    var onFail = function(e) {
      alert('Failed to get camera');
      alert(e);
    };
    var onSuccess = function(stream) {

        if(navigator.mozGetUserMedia) {
            video.mozSrcObject = stream;
        } else {
            var url = window.URL || window.webkitURL;
            video.src = url.createObjectURL(stream);
        }

        // Wait 1000 ms before starting the loop
        setTimeout(function(){

            //rest of functions ...
            //Here I need to use: videoWidth, videoHeight
            //that are obtained from the image data of the camera

        },1000);
    };

    navigator.getUserMedia(options, onSuccess, onFail);

Solution

  • There are two ways: Chrome and Firefox support the new track.getSettings():

    const stream = await navigator.mediaDevices.getUserMedia({video: true});
    const {width, height} = stream.getVideoTracks()[0].getSettings();
    console.log(`${width}x${height}`); // 640x480
    

    This works regardless of whether the stream is hooked up to anything.

    Alternatively, for older browsers, hook the stream up to a video element, and (importantly) wait for metadata to load, before looking at videoWidth and videoHeight:

    video.srcObject = await navigator.mediaDevices.getUserMedia({video: true});
    await new Promise(resolve => video.onloadedmetadata = resolve);
    console.log(`${video.videoWidth}x${video.videoHeight}`); // 640x480
    

    Note that most web cams support more than one resolution. Use constraints for higher resolution:

    await navigator.mediaDevices.getUserMedia({video: {width: 9999}}); // 1280x720
    

    Here's a working fiddle.