logo
post image

Getting Camera Resolution with Javascript

There is no direct method to find out the maximum resolution supported by the camera.

Instead what needs to be done is to request camera access specifying the resolution that we want. Once camera access is given, we can check the resolution of the video stream to find out the actual resolution given by the camera.

In such a case, the ideal property can be used to specify width & height constraints. ideal represents a value that would be ideally required, but if the ideal value is not available — then browser will find a value that is most close to the ideal value.

<button id="start-camera">Start Camera</button>

<script>

document.querySelector("#start-camera").addEventListener('click', async function() {
    // suppose we require a full HD video
    let constraints = { 
                        audio: true, 
                        video: { 
                            width: { ideal: 1920 }, 
                            height: { ideal: 1080 } 
                        }
                    };

    let stream = await navigator.mediaDevices.getUserMedia(constraints);

    let stream_settings = stream.getVideoTracks()[0].getSettings();

    // actual width & height of the camera video
    let stream_width = stream_settings.width;
    let stream_height = stream_settings.height;

    console.log('Width: ' + stream_width + 'px');
    console.log('Height: ' + stream_height + 'px');
});

</script>