Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 822
Norak Avatar asked Dec 01 '17 12:12

Norak


2 Answers

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

let stream = await navigator.mediaDevices.getUserMedia({video: true});
let {width, height} = stream.getTracks()[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.

like image 136
jib Avatar answered Oct 17 '22 00:10

jib


You can get width and height by using videoWidth and videoHeight properties of video element:

video.videoWidth
video.videoWidth

Check live demo

like image 23
Vaidas Avatar answered Oct 16 '22 23:10

Vaidas