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

React中使用getUserMedia调用后置摄像头竖屏全屏问题

解决React中后置摄像头竖屏全屏显示异常问题

1. 修正视频约束的宽高比例

你当前设置的aspectRatio: 6/19不符合竖屏比例标准,竖屏通用比例为9/16(对应1080×1920)。同时避免固定宽高值,改用ideal让浏览器适配设备实际能力:

const constraints = {
  video: {
    facingMode: "environment",
    aspectRatio: { ideal: 9/16 },
    width: { ideal: 1080 },
    height: { ideal: 1920 },
  },
  audio: false,
};

2. 优化Video标签的样式设置

仅靠width="100%" height="100%"无法保证铺满且比例正确,需通过CSS强制铺满容器并保持视频比例:

<video
  autoPlay
  playsInline
  muted
  id="video"
  style={{
    width: '100vw',
    height: '100vh',
    objectFit: 'cover', // 核心:保持视频比例同时铺满屏幕
    position: 'fixed',
    top: 0,
    left: 0,
  }}
/>

3. 横竖屏切换时动态适配(可选)

若需要在设备旋转后自动调整摄像头流,可监听方向变化事件并重新获取媒体流:

// 用React的useRef保存video元素引用
const videoRef = useRef(null);

useEffect(() => {
  const handleOrientationChange = async () => {
    // 停止旧的媒体流
    if (videoRef.current?.srcObject) {
      videoRef.current.srcObject.getTracks().forEach(track => track.stop());
    }

    const isPortrait = window.innerHeight > window.innerWidth;
    const newConstraints = {
      video: {
        facingMode: "environment",
        aspectRatio: { ideal: isPortrait ? 9/16 : 16/9 },
        width: { ideal: isPortrait ? 1080 : 1920 },
        height: { ideal: isPortrait ? 1920 : 1080 },
      },
      audio: false,
    };

    try {
      const mediaStream = await navigator.mediaDevices.getUserMedia(newConstraints);
      videoRef.current.srcObject = mediaStream;
    } catch (err) {
      console.error(`${err.name}: ${err.message}`);
    }
  };

  window.addEventListener('orientationchange', handleOrientationChange);
  return () => window.removeEventListener('orientationchange', handleOrientationChange);
}, []);

4. 兼容性注意事项

  • 确保页面在HTTPS环境下运行(localhost开发不受限制),部分移动端浏览器禁止在HTTP下调用摄像头
  • playsInline属性必须保留,防止iOS设备自动全屏播放视频
  • 避免使用exact约束宽高比例,优先用ideal提高设备适配性

内容的提问来源于stack exchange,提问作者new.user

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 15:15:27