gpt4 book ai didi

Reactjs:如何在 reactjs 中关闭和打开网络摄像头

转载 作者:行者123 更新时间:2023-12-02 00:23:53 30 4
gpt4 key购买 nike

下面的代码用于捕获网络摄像头照片。源链接写在下面 https://www.npmjs.com/package/react-webcam

//npm 安装 react-webcam

这是我的问题,当页面加载时,网络摄像头指针立即打开/激活,我认为这是不正确的。 如果用户不想立即捕获网络摄像头照片。

我的问题是: 无论如何我可以添加一个按钮来通过 reactjs 打开或关闭网络摄像头。为此,我在下面创建了这个按钮,但单击时无法打开相机

 <button onClick={this.setRef}>Turn On/Off Camera</button>

这是主要代码。

import React from "react";
import ReactDOM from "react-dom";

import Webcam from "react-webcam";
class App extends React.Component {


setRef = webcam => {
this.webcam = webcam;
};

capture = () => {
const imageSrc = this.webcam.getScreenshot();
alert(imageSrc);
};



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

return (
<div>
<Webcam
audio={false}
height={350}
ref={this.setRef}
screenshotFormat="image/jpeg"
width={350}
videoConstraints={videoConstraints}
/><br />

<button onClick={this.capture}>Capture and Submit photo</button>
</div>
);
}
}

最佳答案

您的用户会感谢您的谨慎!

我没有使用过 react-webcam,但在我看来你需要做的就是添加一个例如this.state.webcamEnabled属性并呈现 <Webcam />当它为真时不渲染它,当它为假时不渲染它,然后添加一个按钮来切换该属性。像这样的东西(为简洁起见省略了一些代码):

class App extends React.Component {
enableWebcam = () => this.setState({ webcamEnabled: true });

constructor(props) {
super(props);
this.state = { webcamEnabled: false };
}

render() {
// ...
return (
<div>
{this.state.webcamEnabled ? (
<Webcam {...someProps} />
) : (
<button type="button" onClick={this.enableWebcam}>
Enable webcam
</button>
)}
{/* ... */}
</div>
);
}
}

关于Reactjs:如何在 reactjs 中关闭和打开网络摄像头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54443545/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com