mozmorris / react-webcam

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

How to start react-webcam from stopped state without reloading page #321

Closed pawan-khade closed 2 years ago

pawan-khade commented 2 years ago

dear sir,

I have stopped my webcam using code suggested on your codepen

import React,{useEffect,useRef} from "react";
import Webcam from "react-webcam";

function App() {
  const ref = useRef();
  return (
    <div className="App">
      <Webcam ref={ref}/><br/>
      <div>
        <button onClick={()=>{stop(ref);}} >Stop Camera</button> &nbsp;&nbsp;&nbsp;
        <button onClick={()=>{start();}} >Start Camera</button>
      </div>
    </div>
  );
}

//-------------------Function to stop web cam---------------------
function stop(ref) {
  let stream = ref.current.video.srcObject;
    const tracks = stream.getTracks();
    tracks.forEach(track => track.stop());
    ref.current.video.srcObject = null;
}
//----------------------------------------------------------------

Now without refreshing the page I want to start stopped webcam with its video on clicking start button. How to do that?

mozmorris commented 2 years ago

Instead of imperatively stopping the camera, would it not be easier to unmount the component:

const [isActive, setIsActive] = useState(true)

return (
    <div>
        {isActive && <Webcam />}
        <button onClick={() => setIsActive(prev => !prev)} >Toggle Camera</button>
    </div>
)