React网络摄像头设置超时



在React网络摄像头中,有没有一种方法可以检测网络摄像头何时打开?网络摄像头可能需要一些时间才能打开并显示图像。时间似乎在1秒到5秒之间变化,这可能取决于电脑和网络摄像头的速度。如果用户在网络摄像头准备就绪之前单击捕获按钮,则不会保存图像字符串。我试过禁用捕获按钮,然后在5秒时设置Timeout((,然后该按钮将被启用,但这并不准确。我能采取不同的方法吗?非常感谢您的帮助。

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}
/>
</>
)}

我在React Webcam回购文档中找到了答案。网络摄像头组件有一个onUserMedia属性,它使用了一个回调,我将加载设置为false。

https://github.com/mozmorris/react-webcam/issues/74

import React, { Component } from 'react';
import Webcam from 'react-webcam';
class App extends Component {
handleUserMedia = () => {
this.setState({ loading: false });
}
render() {
return (
<Webcam
ref={e => this.webcam = e}
onUserMedia={this.handleUserMedia}
/>
);
}
}
export default App;

在加载相机时,我会使用styleclassName属性来隐藏视频元素

render() {
const display = this.state.loading ? 'none' : 'block';
return (
<>
{this.state.loading && <Loader/>}
<Webcam
onUserMedia={this.handleUserMedia}
style={{display}}
/>
</>
); 
}

最新更新