mozmorris / react-webcam

Webcam component
https://codepen.io/mozmorris/pen/JLZdoP
MIT License
1.65k stars 281 forks source link

Disable WebCam untill I want to use it. #320

Closed DeanVanGreunen closed 2 years ago

DeanVanGreunen commented 2 years ago

Hi, so regarding WebCam.

<div ref={this.ui1}>
    <Webcam screenshotFormat="image/jpeg" audio={false} height={232} width={480} videoConstraints={{width: 1280,height: 720,facingMode: "user"}} id="someUniqueIDHere" ref={this.ui1webcam}></Webcam>
</div>

thats the example element I have, however its hidden via the ref this.ui1 by using this.ui1.current.style.display = "none";

however when this code is run it directly access the WebCam Stream and shows the recording Icon in the browser tab. see image image

now what I would like is if there is a wait to stop/start the stream, so that I can manage when the webcam feed will be accessed, thanks in advance

DeanVanGreunen commented 2 years ago

@mozmorris please assist on adding this feature, thank you.

DeanVanGreunen commented 2 years ago

so something like this.ui1webcam.current.stop() and this.ui1webcam.current.start()

mozmorris commented 2 years ago

I would recommend mounting the once you need it.

// your logic here to set isVisible
const isVisible = true

return (
    <div>
        {isVisible && <Webcam />}
    </div>
)
DeanVanGreunen commented 2 years ago

@mozmorris I have added your suggestions.

constructor(props) {
    super(props);
    this.state = {
      isVisible: false,
    };
    this.cameraRef = createRef();
}
onButtonClick(){
    this.setState({...this.state, isVisible: true});
    this.cameraRef.current.video.style.display = "block"; //line 1238 as per image provided
}

render(){
       let isVisible = this.state.isVisible;   
       return (
       { isVisible && <Webcam style={{width: '100%'}} ref={this.cameraRef} videoConstraints={{facingMode: "user"}}/>}    
  );
}

somehow the ref isnt loading, any idea? I'm still new to react... image

mozmorris commented 2 years ago

You shouldn't be trying to set css properties via refs. And you don't need a ref to Webcam, you can remove it.

If you need to make the Webcam video element display block, you can pass it as a style:

<Webcam style={{ display: block }} />
DeanVanGreunen commented 2 years ago

Perfect, Thank you, close this please.

malavshah9 commented 2 years ago

@mozmorris Still I will need ref to start and stop recording video as per this example:

https://codepen.io/mozmorris/pen/yLYKzyp?editors=0010

DeanVanGreunen commented 2 years ago

@malavshah9 The reason behind my original question was that i only wanted the webcam element to be active when I wanted to use it inorder for it to not access the webcam till required. anyway i have created a work around in my project to support my indended solution