javascript - WebRTC 网络摄像头约束不适应设备方向
问题描述
我正在用 html 和 javascript(实际上是 Angular 1.x)实现一个拍照应用程序。该应用程序主要用于 Android 平板电脑,但也用于手机和 Windows 计算机。
我的问题
是当用户翻转平板电脑(纵向/横向)时,相机也会“翻转”。这意味着,当您将平板电脑置于横向模式时,相机也处于横向模式,而当您翻转平板电脑时,相机处于纵向模式。但系统会保留相机的参数width
和height
参数。
如果我只在哪里显示视频,这不是什么大问题,但我需要复制图像、裁剪、缩放等。所以我需要确保相机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);
}
});
}
}
它是如何工作
的页面加载并且我的脚本将尝试使用 启动网络摄像头{width: 600, height: 480}
,如果导航器无法返回具有这些约束的摄像头,则脚本将继续并测试{width: 320, height: 240}
。
假设导航器可以返回一个带有 的相机320x240
,然后页面将完成加载,我可以显示和操作图像。好的。总是想当然地认为,视频width
是从“左到右”的像素数,它height
从“顶部”到“底部”。
但是,当我在平板电脑上加载页面并将平板电脑翻转到“纵向”模式时,导航器仍然给我带有 的相机{width: 320, height: 240}
,尽管它用width=240
和height=320
(在纵向模式下)显示它。所以现在我所有的图像处理都不再起作用了,因为宽度和高度是相反的。
我的解决方案
所以我想,当页面处于“纵向”模式时(浏览器窗口高于它的宽度),然后我只是反转width
和height
相机。这实际上适用于平板电脑 - 但当然它不适用于台式电脑。
所以这是我的实际问题 如果整个设备处于“纵向”或“横向”模式而不依赖于浏览器的宽度和高度,是否有办法查询“导航器”?
解决方案
如果您确定它不一定需要在 safari 上工作。您可以使用屏幕 API。
https://developer.mozilla.org/en-US/docs/Web/API/Screen/orientation
在该页面中,您有一个示例。
推荐阅读
- django - 无法登录到 Django 管理面板
- json - 定义一个“平面”的 OpenAPI 文档模式?
- python - 在 1 个脚本中运行 2 个永久运行的函数
- angularjs - 参数“...”隐式具有“任何”类型
- microsoft-graph-api - 如何通过 Microsoft Graph Api 正确请求 Sharepoint Online 站点权限
- java - java中的电子邮件验证循环不起作用
- excel - 将“findnext”功能合并到现有的“查找”代码中?
- tensorflow - 如何使用 CNN 和 LSTM 元素改进文本分类模型?
- r - 如何使用 autoplot 和 geom_scatterpie
- typescript - 如何连接 observables 与下一个观察者发出