You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android手机上通过navigator.mediaDevices.getUserMedia调用竖置摄像头?

解决移动端Chrome竖屏调用摄像头返回横屏流的问题

问题核心

移动端摄像头传感器大多为横屏原生输出,即使通过getUserMedia请求竖屏比例,浏览器可能因硬件限制返回原生横屏流,同时会通过视频轨道的videoRotation参数告知需要旋转的角度,这是你遇到问题的主要原因。

修正方案

1. 优化摄像头约束配置

不要仅依赖aspectRatio,同时明确指定宽高的理想值,并补充facingMode(可选,明确前置/后置摄像头),让浏览器更精准匹配需求:

const isPortrait = !this.isLandscape();
const targetWidth = isPortrait ? 1080 : 1920;
const targetHeight = isPortrait ? 1920 : 1080;

const cameraConstraints = {
  video: {
    deviceId: deviceId,
    facingMode: "environment", // 后置摄像头,如需前置改为"user"
    width: { ideal: targetWidth, max: targetWidth },
    height: { ideal: targetHeight, max: targetHeight },
    aspectRatio: { ideal: targetWidth / targetHeight }
  }
};

2. 处理视频旋转角度

即使浏览器返回横屏流,视频轨道的设置中包含videoRotation字段,通过该值调整视频渲染的旋转角度,实现竖屏显示:

navigator.mediaDevices.getUserMedia(cameraConstraints).then(stream => {
  const videoTrack = stream.getVideoTracks()[0];
  const trackSettings = videoTrack.getSettings();
  // 获取浏览器返回的旋转角度(通常为90或270度,对应竖屏需求)
  const rotation = trackSettings.videoRotation || 0;

  const videoElement = document.getElementById('your-video-element');
  videoElement.srcObject = stream;

  // 根据旋转角度调整视频显示
  if (rotation !== 0) {
    // 旋转后视频实际显示宽高交换
    videoElement.style.width = `${targetHeight}px`;
    videoElement.style.height = `${targetWidth}px`;
    videoElement.style.transform = `rotate(${rotation}deg)`;
    videoElement.style.transformOrigin = 'center center';
  }
});

关键说明

  • 移动端Chrome对aspectRatio的严格约束支持有限,优先通过width/height的ideal参数引导浏览器匹配需求。
  • 摄像头硬件原生输出为横屏是行业普遍情况,无法强制改变流的原始比例,只能通过渲染阶段的旋转实现竖屏显示。
  • 不同设备的videoRotation值可能不同(90/270度),必须通过轨道设置动态获取,不要写死固定值。

内容的提问来源于stack exchange,提问作者Bruno Lamps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 03:12:50