首页 > 解决方案 > React 网络摄像头设置超时

问题描述

在 React Webcam 中,有没有办法检测网络摄像头何时开启?网络摄像头可能需要一些时间才能打开并显示图像。时间似乎在 1 秒到 5 秒之间变化,这可能取决于计算机和网络摄像头的速度。如果用户在网络摄像头准备好之前单击捕获按钮,则不会保存图像字符串。我尝试禁用捕获按钮,然后在 5 秒时禁用 setTimeout(),然后该按钮将被启用,但它不准确。我可以采取不同的方法吗?任何帮助是极大的赞赏。

const videoConstraints = {
  width: 1280,
  height: 720,
  facingMode: "user"
};

const WebcamCapture = () => {
  const webcamRef = React.useRef(null);

  const capture = React.useCallback(
    () => {
      const imageSrc = webcamRef.current.getScreenshot();
    },
    [webcamRef]
  );

  return (
    <>
      <Webcam
        audio={false}
        height={720}
        ref={webcamRef}
        screenshotFormat="image/jpeg"
        width={1280}
        videoConstraints={videoConstraints}
      />
      <button onClick={capture}>Capture photo</button>
    </>
  );
};

我在使用 onUserMedia 时遇到问题。我想在网络摄像头打开时添加一个加载微调器。似乎我必须在我的三元运算符中使用第二个网络摄像头组件才能使用 onUserMedia。它会导致网络摄像头打开和关闭四次。有没有另一种方法可以在不使用两个网络摄像头组件的情况下添加加载微调器?任何帮助是极大的赞赏。

handleUserMedia = () => {
        this.setState({ showLoader: false });
    };

this.state.showLoader ? (
                 <div>
                     <Loader />
                     <p>Starting Camera...</p>
                     <div className="loading-webcam">
                          <Webcam onUserMedia={this.handleUserMedia} />
                     </div>
                 </div>
            ) : (
                 <>
                    <Webcam
                           audio={false}
                           height={365}
                           ref={this.setRef}
                     />
                  </>
             )}

标签: reactjswebcamwebcam-capture

解决方案


我会在加载相机时使用styleor属性隐藏视频元素className

render() {
  const display = this.state.loading ? 'none' : 'block';

  return (
    <>
      {this.state.loading && <Loader/>}
      <Webcam
        onUserMedia={this.handleUserMedia}
        style={{display}}
      />
    </>
  ); 
}

推荐阅读