Capture real-time images and videos with React-Webcam
Tags: javascript, react, webcam
Published: 2022-10-17 23:28:11

by [Clarence Bakosi](https://blog.openreplay.com/authors/clarence-bakosi)


Webcams are video cameras that work well for recording in-progress pictures or videos for your web applications. It is recognized to help with streaming, instant messaging, video conferencing, and other related activities. Webcams have recently evolved into crucial tools for the social and business worlds, respectively.

[React-Webcam](https://www.npmjs.com/package/react-webcam) is a lightweight JavaScript library with [weekly downloads](https://www.npmjs.com/package/react-webcam) of over 113k on npm and 1.3k stars on [GitHub](https://github.com/mozmorris/react-webcam). It supports both mobile and laptop devices that have physical or embedded webcams. The library includes several adaptable functions that make it simple to integrate into your application.


In this article, we will look at how to include react-webcam into your application and create a small webcam-based web application that will provide the following features:
- Choosing a camera
- Capturing Images
- Smoothing Images
- Capturing Video



## Installing react-webcam

In this section, we will look at how to implement react-webcam into your react application and use the functionality that it supports.

To begin, run the React application using the instructions shown below.

```
 npx create-react-app react-webcam
```

Install dependencies:

```
 cd react-webcam
 npm i react-webcam
 npm start
```

Next, we modify `App.css` to add some basic styling to the application.

```
.App {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  background-color: #282c34;

}

.Container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  margin: 0 10px;
}

img {
  height: 400px;
  width: 400px;
  object-fit: cover;
}

button {
  background-color: crimson;
  color: #fff;
  margin-top: 10px;
  padding: 10px 40px;
  border: none;
  border-radius: 25px;
  cursor: pointer;
}
```

## Build Webcam Component
In this section, we will import the webcam component into the `App.js` component.

```javascript
import React from "react";
import Webcam from "react-webcam";
import "./App.css";

function App() {
  return (
    <div className="App">
      <Webcam />
    </div>
  );
}

export default App;
```

A prompt will pop up on your screen; you have to click allow.

![1 Dialog box](https://blog.openreplay.com/images/capture-real-time-images-and-videos-with-react-webcam/images/image01.png)



The component should now have access to your machine when you click `Allow`.

![2 Image of the webcam output](https://blog.openreplay.com/images/capture-real-time-images-and-videos-with-react-webcam/images/image02.jpg)


## The react-webcam props
The react-webcam component has several props that you may utilize in your application. We'll go through a couple of them below:

### Image Smoothing

This prop smoothens the pixel of a screenshot taken. It is a boolean.

```javascript
<Webcam imageSmoothing={true} />
```

### Audio

The audio prop is a boolean with a default value of `false`. This controls the state of the computer's microphone.

```javascript
<Webcam audio={true} />
```
After adding the audio prop to the webcam component, we will get a prompt requesting to allow access to the computer's microphone.

![3 Allow mic](https://blog.openreplay.com/images/capture-real-time-images-and-videos-with-react-webcam/images/image03.png)


### Screenshot Format

The screenshot format prop has a type of `string` and a default value of `'image/webp.'` 

```javascript
<Webcam screenshotFormat='image/webp' />
```

### Mirrored

The mirrored prop is a boolean, with a default value of `false` This gives a mirrored version of the webcam's output.
```javascript
<Webcam mirrored={false} />
```

![4 not mirrored output](https://blog.openreplay.com/images/capture-real-time-images-and-videos-with-react-webcam/images/image04.jpg)



Following this, we will set the mirrored prop to `true`. 
```javascript
<Webcam mirrored={true} />
```
![5 mirrored output](https://blog.openreplay.com/images/capture-real-time-images-and-videos-with-react-webcam/images/image05.jpg)


### Video Constraints
The `videoConstraints` prop is a type of object that handles the values of the `width`, `height`, `aspect ratio`, and `facingMode` of a video. The aspect ratio value can change the camera layout to landscape or portrait. 

```javascript
const videoConstraints = {
  width: { min: 480 },
  height: { min: 720 },
  aspectRatio: 0.6666666667,
  facingMode: "user"
};

...
<Webcam width={480} height={720} videoConstraints={videoConstraints} />
```

![6 Portrait layout](https://blog.openreplay.com/images/capture-real-time-images-and-videos-with-react-webcam/images/image06.jpg)


### Front and back camera
For devices with front and back cameras, react-webcam allows you to flip between them. It accomplishes this by utilizing the `videoConstraints` prop. The code below uses the front camera.

```javascript
function App() {
  const videoConstraints = {
    width: { min: 480 },
    height: { min: 720 },
    facingMode: "user",
  };

  return (
    <div className="App">
      <Webcam width={480} height={720} videoConstraints={videoConstraints} />
    </div>
  );
}
```

The code below uses the rear camera.

```javascript
function App() {
  const videoConstraints = {
    width: { min: 480 },
    height: { min: 720 },
    facingMode: { exact: "environment" }
  };

  return (
    <div className="App">
      <Webcam width={480} height={720} videoConstraints={videoConstraints} />
    </div>
  );
}

```



![OpenReplay](https://blog.openreplay.com/banner-blog_1oYPGT.png)

_Start enjoying your debugging experience - <a href="https://github.com/openreplay/openreplay" >start using OpenReplay for free</a>._





## Capture Image

In this section, we will extend the webcam's functionality by combining two or more props to enable the application to capture a real-time image. We will utilize the `getScreenshot` method, which returns a [base64](https://en.wikipedia.org/wiki/Base64) encoded string of the current webcam image.

Next, we will create a `WebcamImage.js` component and paste the code block below:

```javascript
import React, { useCallback, useRef, useState } from "react";
import Webcam from "react-webcam";

function WebcamImage() {
  const [img, setImg] = useState(null);
  const webcamRef = useRef(null);

  const videoConstraints = {
    width: 420,
    height: 420,
    facingMode: "user",
  };

  const capture = useCallback(() => {
    const imageSrc = webcamRef.current.getScreenshot();
    setImg(imageSrc);
  }, [webcamRef]);

  return (
    <div className="Container">
      {img === null ? (
        <>
          <Webcam
            audio={false}
            mirrored={true}
            height={400}
            width={400}
            ref={webcamRef}
            screenshotFormat="image/jpeg"
            videoConstraints={videoConstraints}
          />
          <button onClick={capture}>Capture photo</button>
        </>
      ) : (
        <>
          <img src={img} alt="screenshot" />
          <button onClick={() => setImg(null)}>Retake</button>
        </>
      )}
    </div>
  );
}

export default WebcamImage;

```

Next, We modify `App.js` by pasting the code block below:

```javascript
import React from "react";
import WebcamImage from "./WebcamImage";
import "./App.css";

function App() {
  return (
    <div className="App">
      <WebcamImage />
    </div>
  );
}

export default App;
```

![7 Capture Image](https://blog.openreplay.com/images/capture-real-time-images-and-videos-with-react-webcam/images/image07.gif)



## Capture Video

In this section, we'll add to the react-webcam's functionality by recording a live video and saving it to your computer.

Next, We will create a `WebcamVideo.js` component and paste the code block below:

```javascript
import React, { useCallback, useRef, useState } from "react";
import Webcam from "react-webcam";

export default function WebcamVideo() {
  const webcamRef = useRef(null);
  const mediaRecorderRef = useRef(null);
  const [capturing, setCapturing] = useState(false);
  const [recordedChunks, setRecordedChunks] = useState([]);

  const handleDataAvailable = useCallback(
    ({ data }) => {
      if (data.size > 0) {
        setRecordedChunks((prev) => prev.concat(data));
      }
    },
    [setRecordedChunks]
  );

  const handleStartCaptureClick = useCallback(() => {
    setCapturing(true);
    mediaRecorderRef.current = new MediaRecorder(webcamRef.current.stream, {
      mimeType: "video/webm",
    });
    mediaRecorderRef.current.addEventListener(
      "dataavailable",
      handleDataAvailable
    );
    mediaRecorderRef.current.start();
  }, [webcamRef, setCapturing, mediaRecorderRef, handleDataAvailable]);

  const handleStopCaptureClick = useCallback(() => {
    mediaRecorderRef.current.stop();
    setCapturing(false);
  }, [mediaRecorderRef, setCapturing]);

  const handleDownload = useCallback(() => {
    if (recordedChunks.length) {
      const blob = new Blob(recordedChunks, {
        type: "video/webm",
      });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      document.body.appendChild(a);
      a.style = "display: none";
      a.href = url;
      a.download = "react-webcam-stream-capture.webm";
      a.click();
      window.URL.revokeObjectURL(url);
      setRecordedChunks([]);
    }
  }, [recordedChunks]);

  const videoConstraints = {
    width: 420,
    height: 420,
    facingMode: "user",
  };

  return (
    <div className="Container">
      <Webcam
        height={400}
        width={400}
        audio={false}
        mirrored={true}
        ref={webcamRef}
        videoConstraints={videoConstraints}
      />
      {capturing ? (
        <button onClick={handleStopCaptureClick}>Stop Capture</button>
      ) : (
        <button onClick={handleStartCaptureClick}>Start Capture</button>
      )}
      {recordedChunks.length > 0 && (
        <button onClick={handleDownload}>Download</button>
      )}
    </div>
  );
}
```

Next, We update `App.js` by pasting the code block below:

```javascript
import React from "react";
import WebcamVideo from "./WebcamVideo";
import "./App.css";

function App() {

  return (
    <div className="App">
      <WebcamVideo/>
    </div>
  );
}

export default App;

```

![8 Video record](https://blog.openreplay.com/images/capture-real-time-images-and-videos-with-react-webcam/images/image08.gif)

Below is the output of the video captured above

![9 Video output](https://blog.openreplay.com/images/capture-real-time-images-and-videos-with-react-webcam/images/image09.gif)




## Conclusion

In this article, we demonstrated how to use react-webcam to capture images and videos on a real-time basis. I hope this article has helped you take advantage of its features. If you want to go at the code for this post, visit the [GitHub Repository](https://github.com/clarencepenz/react-webcam).



> A TIP FROM THE EDITOR: You could complement the video capture with a conversion to GIF, as shown in the [Convert Videos to GIF format for speed](https://blog.openreplay.com/convert-videos-to-gif-format-for-speed) article.


<h2>Open Source Session Replay</h2> 

_<a href="https://github.com/openreplay/openreplay" target="_blank">OpenReplay</a> is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data._




[![newsletter](https://blog.openreplay.com/newsletter_Z1P0UIP.png)](https://newsletter.openreplay.com/)