react-webcam

repository·master·Indexed 23 days ago

https://github.com/mozmorris/react-webcam

A React component for accessing a user's webcam, managing video and audio constraints, and capturing screenshots. It provides a wrapper around the browser's getUserMedia API and supports screenshot capture via the getScreenshot() method, accessible through either a React ref or a render props pattern. Version 7.1.1.

Tokens
2.7K
Snippets
8
Records
14
Agent score
33%

What's inside react-webcam

  1. Configure video constraints

    master
    The videoConstraints prop accepts an object that is passed to the getUserMedia method. This allows you to specify requirements like resolution or camera direction. Refer to MDN's getUserMedia and MediaStreamConstraints documentation for full details.
  2. Mirrored video with non-mirrored screenshots

    master

    If you use the mirrored prop, both the preview and the screenshot will be mirrored. To show a mirrored preview but capture a standard (non-mirrored) screenshot, use the mirrored prop for the component and apply a CSS transform to the video element instead:

    video {
      transform: scaleX(-1);
    }
  3. Select specific cameras using facingMode

    master

    You can control which camera to use by setting the facingMode within the videoConstraints object.

    User/Selfie/forward facing camera:

    const videoConstraints = {
      facingMode: "user"
    };

    Environment/Facing-Out camera:

    const videoConstraints = {
      facingMode: { exact: "environment" }
    };
    // Example: Environment camera
    class WebcamCapture extends React.Component {
      render() {
        const videoConstraints = {
          facingMode: { exact: "environment" }
        };
    
        return <Webcam videoConstraints={videoConstraints} />;
      }
    }
  4. Use the Webcam component

    master

    The Webcam component provides a React wrapper around the browser's getUserMedia API to display a video stream and capture screenshots. It can be used as a standard component or with a render prop pattern to access the getScreenshot method.

    Render Prop Pattern

    To capture screenshots, pass a function as a child to the Webcam component. This function receives a childrenProps object containing the getScreenshot method.

    <Webcam>
      {(screenshotProps) => (
        <button onClick={() => console.log(screenshotProps.getScreenshot())}>
          Take Screenshot
        </button>
      )}
    </Webcam>
  5. Use Webcam inside an iframe

    master

    When using the Webcam component inside a cross-origin iframe, newer versions of Chrome (v64+) will block access unless the allow attribute is explicitly set on the <iframe> tag to include camera and microphone permissions.

    <iframe src="https://my-website.com/page-with-webcam" allow="camera; microphone;"/>
  6. Basic Usage of Webcam component

    master

    Import the Webcam component and render it within your React application. Note that browsers require the page to be loaded from a secure origin (HTTPS) to access the camera.

    import React from "react";
    import Webcam from "react-webcam";
    
    const WebcamComponent = () => <Webcam />;
  7. Capture a screenshot via render props

    master

    You can access the getScreenshot method by using the render props pattern provided by the Webcam component.

    const videoConstraints = {
      width: 1280,
      height: 720,
      facingMode: "user"
    };
    
    const WebcamCapture = () => (
      <Webcam
        audio={false}
        height={720}
        screenshotFormat="image/jpeg"
        width={1280}
        videoConstraints={videoConstraints}
      >
        {({ getScreenshot }) => (
          <button
            onClick={() => {
              const imageSrc = getScreenshot()
            }}
          >
            Capture photo
          </button>
        )}
      </Webcam>
    );
  8. List and select all available cameras

    master

    To allow a user to choose from multiple cameras, use navigator.mediaDevices.enumerateDevices() to find all videoinput devices and pass the specific deviceId to the videoConstraints prop.

    const WebcamCapture = () => {
      const [deviceId, setDeviceId] = React.useState({});
      const [devices, setDevices] = React.useState([]);
    
      const handleDevices = React.useCallback(
        mediaDevices =>
          setDevices(mediaDevices.filter(({ kind }) => kind === "videoinput")),
        [setDevices]
      );
    
      React.useEffect(
        () => {
          navigator.mediaDevices.enumerateDevices().then(handleDevices);
        },
        [handleDevices]
      );
    
      return (
        <>
          {devices.map((device, key) => (
              <div key={key}>
                <Webcam audio={false} videoConstraints={{ deviceId: device.deviceId }} />
                {device.label || `Device ${key + 1}`}
              </div>
            ))}
        </>
      );
    };
  9. Capture a screenshot via ref

    master

    Alternatively, you can use a React ref to access the getScreenshot method directly from the component instance.

    const videoConstraints = {
      width: 1280,
      height: 720,
      facingMode: "user"
    };
    
    const WebcamCapture = () => {
      const webcamRef = React.useRef(null);
      const capture = React.useCallback(
        () => {
          const imageSrc = webcamRef.current.getScreenshot();
        },
        [webcamRef]
      );
      return (
        <>
          <Webcam
            audio={false}
            height={720}
            ref={webcamRef}
            screenshotFormat="image/jpeg"
            width={1280}
            videoConstraints={videoConstraints}
          />
          <button onClick={capture}>Capture photo</button>
        </>
      );
    };
  10. Webcam component props

    master

    The Webcam component accepts several props to configure the stream and screenshot behavior. You can also pass any standard prop supported by the underlying HTML <video> tag (e.g., className, style, muted).

    proptypedefaultnotes
    audiobooleanfalseenable/disable audio
    audioConstraintsobjectMediaStreamConstraint(s) for the audio
    disablePictureInPicturebooleanfalsedisable Picture-in-Picture
    forceScreenshotSourceSizebooleanfalseuses size of underlying source video stream (and thus ignores other size related props)
    imageSmoothingbooleantruepixel smoothing of the screenshot taken
    mirroredbooleanfalseshow camera preview and get the screenshot mirrored
    minScreenshotHeightnumbermin height of screenshot
    minScreenshotWidthnumbermin width of screenshot
    onUserMediafunctionnoopcallback for when component receives a media stream
    onUserMediaErrorfunctionnoopcallback for when component can't receive a media stream with MediaStreamError param
    screenshotFormatstring'image/webp'format of screenshot
    screenshotQualitynumber0.92quality of screenshot(0 to 1)
    videoConstraintsobjectMediaStreamConstraints(s) for the video