如何实现react-webcam响应式,适配全设备全屏显示
适配全设备的响应式摄像头捕获实现
核心修改逻辑
- 动态监听窗口尺寸变化,实时更新视频捕获参数,避免初始化后尺寸固定无法适配窗口调整
- 新增
object-fit属性处理摄像头原生比例与视口比例不匹配的问题,无黑边铺满全屏 - 全局样式清除默认边距,保证视口占满无滚动条
完整JS代码
import React, { useCallback, useRef, useState, useEffect } from 'react'; import Webcam from 'react-webcam'; import RadioButtonUncheckedIcon from '@material-ui/icons/RadioButtonUnchecked'; import { useDispatch } from 'react-redux'; import { setCameraImage } from './features/cameraSlice'; import { useHistory } from 'react-router-dom'; import './WebcamCapture.css'; function WebcamCapture() { const webcamRef = useRef(null); const dispatch = useDispatch(); const history = useHistory(); // 动态存储视频约束参数 const [videoConstraints, setVideoConstraints] = useState({ width: window.innerWidth, height: window.innerHeight, facingMode: 'environment', }); // 监听窗口resize事件,实时更新视频尺寸 useEffect(() => { const handleResize = () => { setVideoConstraints(prev => ({ ...prev, width: window.innerWidth, height: window.innerHeight, })); }; window.addEventListener('resize', handleResize); return () => window.removeEventListener('resize', handleResize); }, []); const capture = useCallback(() => { const imageSrc = webcamRef.current.getScreenshot(); dispatch(setCameraImage(imageSrc)); history.push('/preview'); }, [webcamRef, dispatch, history]); return ( <div className="webcamCapture"> <Webcam audio={false} ref={webcamRef} screenshotFormat="image/jpeg" videoConstraints={videoConstraints} /> <RadioButtonUncheckedIcon className="webcamCapture__button" onClick={capture} fontSize="large" /> </div> ); } export default WebcamCapture;
完整CSS代码
/* 全局样式清除默认边距,保证占满视口 */ * { margin: 0; padding: 0; box-sizing: border-box; } html, body { width: 100%; height: 100%; overflow: hidden; } .webcamCapture { position: relative; width: 100vw; height: 100vh; overflow: hidden; } /* 强制video元素铺满容器,比例不匹配时自动裁切无黑边 */ .webcamCapture video { width: 100%; height: 100%; object-fit: cover; } .webcamCapture__button { position: absolute; bottom: 30px; left: 50%; transform: translateX(-50%); cursor: pointer; color: white; z-index: 10; }
内容的提问来源于stack exchange,提问作者Rohit Rai
相关产品推荐
相关产品推荐

