9

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);
Norak
  • 383
  • 2
  • 6
  • 14
  • You can set the video constraints in your options like video: { width: 1280, height: 720 }..check https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia – Albeis Dec 01 '17 at 12:29
  • Or something like: videoWidth = video.videoWidth; videoHeight = video.videoHeight; – Albeis Dec 01 '17 at 12:32

2 Answers2

21

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.

dearsina
  • 4,774
  • 2
  • 28
  • 34
jib
  • 40,579
  • 17
  • 100
  • 158
3

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

video.videoWidth
video.videoWidth

Check live demo

Vaidas
  • 1,494
  • 14
  • 21