WebRTC 网络摄像头约束不适应设备方向

Gam*_*ids 10 html javascript android webrtc

我正在用 html 和 javascript(实际上是 Angular 1.x)实现一个拍照应用程序。该应用程序主要用于 Android 平板电脑,但也用于手机和 Windows 计算机。

我的问题
当用户翻转平板电脑(纵向/横向)时,相机也会“翻转”。这意味着,当您以横向模式握住平板电脑时,相机也处于横向模式,而当您翻转平板电脑时,相机处于纵向模式。但是系统会保留摄像机的参数widthheight参数。

在此处输入图片说明

如果我只在何处显示视频,这不会有太大问题,但我需要复制图像、裁剪、缩放等。所以我需要确保相机的width实际上是width.

我的实现
为了给你一个想法,我试图提取负责相机的代码:

// I have a static array with possible camera resolutions
private resolutions = [
    {width: 320, height: 240},
    {width: 600, height: 480}
];

// and the camera constraints that I initialize like this
this.constraints = {
    audio: false,                  // no audio needed
    video: {
        facingMode: "environment", // I want the back camera
        width: {
            exact: 4096            // initial width 
        },
        height: {
            exact: 2160            // initial height
        }
    }
};

// I use that array to query the system for a camera that fits these resolution constraints (it's recursive, so I call this function with the last index of my resolutions-array)
testCameraResolution(resolutionIndex: number) {
    if (this.checking) {
        this.constraints.video.width.exact = this.resolutions[resolutionIndex].width;    // overwrite the width value of the constraints
        this.constraints.video.height.exact = this.resolutions[resolutionIndex].height;   // overwrite the height value of the constraints
        navigator.mediaDevices.getUserMedia(this.constraints).then((stream: MediaStream) => {
            // when the navigator returns a camera with these constraints, I found my resolution and can stop testing.
            this.checking = false;  
            for (let track of stream.getTracks()) {
                track.stop();   // I stop the camera stream
            }
            this.videoResolution.width = this.constraints.video.width.exact;
            this.videoResolution.height = this.constraints.video.height.exact;
            this.startWebCam();  // and start the webcam
        }).catch((error) => {
            // no camera was found that matches these constraints, continue testing
            if (resolutionIndex > 0) {
                this.testCameraResolution(resolutionIndex - 1);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

工作原理
页面加载,我的脚本将尝试使用 启动网络摄像头{width: 600, height: 480},如果导航器无法返回具有这些约束的摄像头,脚本将继续并测试{width: 320, height: 240}

假设导航器可以使用 返回相机320x240,然后页面将完成加载,我可以显示和操作图像。好的。总是认为这是理所当然的,视频width是从“左到右”的像素数,它是height从“顶部”到“底部”的跨度。

但是当我在平板电脑上加载页面并将平板电脑翻转到“纵向”模式时,导航器仍然给我带 的相机{width: 320, height: 240},尽管它用width=240和显示它height=320(在纵向模式下)。所以现在我所有的图像处理都不再起作用了,因为宽度和高度是相反的。

我的解决方案
所以我想,当页面是“肖像”模式(浏览器窗口高于其宽度),然后我就反widthheight相机。这实际上适用于平板电脑 - 但当然它不适用于台式计算机。

所以这是我的实际问题 如果整个设备处于“纵向”或“横向”模式,是否有办法在不依赖浏览器宽度和高度的情况下查询“导航器”?

Nic*_*ile 1

如果你确定它不一定需要在 safari 上工作。您可以使用屏幕 API。

https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation

在该页面中您有一个示例。