Search code examples
javascriptwebrtcgetusermedia

How to get webcam stream with aspect ratio 1:1 and maximum available resolution


Basically the question is in the title. This is about WebRTC and getUserMedia function. Similar question was here: How to keep 1:1 aspect ratio video all the time in WebRTC. But in my case I need to record a stream using MediaRecorder, just crop a video element with css is not enough. I'm a bit confused about getUserMedia constraints. There is aspectRatio parameter, but I didn't manage how to achieve required result with it. What worked for me was to define constraints in that way:

const constraints = {
  audio: true,
  video: {
    width: { exact: 720 },
  }
};

But it doesn't define max resolution automatically. Do you have any ideas how to do it in a smart way?


Solution

  • Not all cameras are going to support all aspect ratios. 1:1 is certainly an oddball aspect ratio.

    What you have to do is do your own cropping and make your own stream. You can do this by setting a video's srcObject to the getUserMediaStream, then every frame (use requestAnimationFrame()), draw that video to a canvas, in whatever cropped way you want. From there, use CanvasCaptureMediaStream to get the edited video back out as a stream which you can use in your WebRTC call.