Skip to content

Instantly share code, notes, and snippets.

@keveman
Created April 8, 2023 22:55
Show Gist options
  • Save keveman/a94c53693647869b47a68ee586a4e67b to your computer and use it in GitHub Desktop.
Save keveman/a94c53693647869b47a68ee586a4e67b to your computer and use it in GitHub Desktop.
React Webcam Switch Camera Example
<div id="root"></div>
const FACING_MODE_USER = "user";
const FACING_MODE_ENVIRONMENT = "environment";
const videoConstraints = {
facingMode: FACING_MODE_USER
};
const WebcamCapture = () => {
const [facingMode, setFacingMode] = React.useState(FACING_MODE_USER);
const handleClick = React.useCallback(() => {
setFacingMode(
prevState =>
prevState === FACING_MODE_USER
? FACING_MODE_ENVIRONMENT
: FACING_MODE_USER
);
}, []);
return (
<>
<button onClick={handleClick}>Switch camera</button>
<Webcam
audio={false}
screenshotFormat="image/jpeg"
videoConstraints={{
...videoConstraints,
facingMode
}}
/>
</>
);
};
ReactDOM.render(<WebcamCapture />, document.getElementById("root"));
// https://www.npmjs.com/package/react-webcam
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/[email protected]/prop-types.js"></script>
<script src="https://unpkg.com/react-webcam/dist/react-webcam.min.js"></script>
button,
video {
display: block;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment