Welcome folks today in this blog post we will be building a react.js webcam capture
and camera selfie app
using react-webcam
library in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a react.js
project using the below command as shown below
npx create-react-app sampleapp
cd sampleapp
And now you need to install the library
using the npm command as shown below
npm i react-webcam
And now you need to edit the App.js
file and copy paste the following code
App.js
1 2 3 4 5 6 7 8 9 10 11 12 |
import React from "react"; import "./styles.css"; import Camera from "./Camera"; export default function App() { return ( <div className="App"> <Camera /> </div> ); } |
As you can see are including the Camera
component in which we will be taking the screenshot
of the user webcam. Now we need to create the Camera.js
file and copy paste the following code
Camera.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import React, {useRef } from "react"; import Webcam from "react-webcam"; const videoConstraints = { width: 540, facingMode: "environment" }; const Camera = () => { const webcamRef = useRef(null); const [url, setUrl] = React.useState(null); const capturePhoto = React.useCallback(async () => { const imageSrc = webcamRef.current.getScreenshot(); setUrl(imageSrc); }, [webcamRef]); const onUserMedia = (e) => { console.log(e); }; return ( <> <Webcam ref={webcamRef} audio={true} screenshotFormat="image/jpeg" videoConstraints={videoConstraints} onUserMedia={onUserMedia} /> <button onClick={capturePhoto}>Capture</button> <button onClick={() => setUrl(null)}>Refresh</button> {url && ( <div> <img src={url} alt="Screenshot" /> </div> )} </> ); }; export default Camera; |
As you can see we are importing the react-webcam
library to take pictures
from the user webcam. And inside this component we have two buttons to capture
the picture from the webcam. And also we have the img
tag where we will be showing the captured photo
from the webcam. And we are using the Webcam
component to display the user webcam
And now to take screenshot we are using the getScreenshot()
method to take the picture from the webcam