react-webcam allows you to implement camera shooting functionality in your React app.
Click [Start] in the above demo to start the camera. If you are asked for camera shooting permission, please allow it. (We do not send the captured data to the outside)
Then the image captured by the camera is displayed. Also, [Exit] on the upper left is the end of camera shooting, and [Capture] on the lower left is the button to capture the captured image.
Then the image captured by the camera is displayed. Also, [Exit] on the upper left is the button to end the camera shooting, and [Capture] on the lower left is the button to capture the captured video.
When capturing, the capture of the captured video was displayed.
import { useRef, useState, useCallback } from "react";
import Webcam from "react-webcam";
import "./styles.css";
const videoConstraints = {
width: 720,
height: 360,
facingMode: "user"
};
export const App = () => {
const [isCaptureEnable, setCaptureEnable] = useState<boolean>(false);
const webcamRef = useRef<Webcam>(null);
const [url, setUrl] = useState<string | null>(null);
const capture = useCallback(() => {
const imageSrc = webcamRef.current?.getScreenshot();
if (imageSrc) {
setUrl(imageSrc);
}
}, [webcamRef]);
return (
<>
<header>
<h1>camera app</h1>
</header>
{isCaptureEnable || (
<button onClick={() => setCaptureEnable(true)}>start</button>
)}
{isCaptureEnable && (
<>
<div>
<button onClick={() => setCaptureEnable(false)}>end </button>
</div>
<div>
<Webcam
audio={false}
width={540}
height={360}
ref={webcamRef}
screenshotFormat="image/jpeg"
videoConstraints={videoConstraints}
/>
</div>
<button onClick={capture}>capture</button>
</>
)}
{url && (
<>
<div>
<button
onClick={() => {
setUrl(null);
}}
>
delete
</button>
</div>
<div>
<img src={url} alt="Screenshot" />
</div>
</>
)}
</>
);
};
Top comments (2)
I rarely sign up on sites to comment, but I really wanted to thank you for this! It helped me work around a lint / type related problem that I can't figure out.
thanks, it makes me happy