7.2.0 • Published 6 months ago

react-webcam v7.2.0

Weekly downloads
45,690
License
MIT
Repository
github
Last release
6 months ago

react-webcam

Build Status downloads

DEMO: https://codepen.io/mozmorris/pen/JLZdoP

https://www.npmjs.com/package/react-webcam

Webcam component for React. See http://caniuse.com/#feat=stream for browser compatibility.

Note: Browsers will throw an error if the page is loaded from insecure origin. I.e. Use https.

Installation

# with npm
npm install react-webcam

# with yarn
yarn add react-webcam

Demo

https://codepen.io/mozmorris/pen/JLZdoP

Usage

import React from "react";
import Webcam from "react-webcam";

const WebcamComponent = () => <Webcam />;

Props

The props here are specific to this component but one can pass any prop to the underlying video tag eg className, style, muted, etc

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

Methods

getScreenshot - Returns a base64 encoded string of the current webcam image. Example:

https://codepen.io/mozmorris/pen/gOOoqpw

You may also pass in an optional dimensions object:

getScreenshot({width: 1920, height: 1080});

The Constraints

We can build a constraints object by passing it to the videoConstraints prop. This gets passed into getUserMedia method. Please take a look at the MDN docs to get an understanding how this works.

https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia https://developer.mozilla.org/en-US/docs/Web/API/Media_Streams_API/Constraints

As an example take a look at this CodePen demo https://codepen.io/mozmorris/pen/GRpEQwK?editors=0010 which shows how to build a custom aspect ratio for the video.

Screenshot (via render props)

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>
);

Screenshot (via ref)

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>
    </>
  );
};

Capturing video

It is posible to capture video with <Webcam /> using the MediaStream Recording API.

You can find an example https://codepen.io/mozmorris/pen/yLYKzyp?editors=0010.

Choosing a camera

User/Selfie/forward facing camera

class WebcamCapture extends React.Component {
  render() {
    const videoConstraints = {
      facingMode: "user"
    };

    return <Webcam videoConstraints={videoConstraints} />;
  }
}

Environment/Facing-Out camera

class WebcamCapture extends React.Component {
  render() {
    const videoConstraints = {
      facingMode: { exact: "environment" }
    };

    return <Webcam videoConstraints={videoConstraints} />;
  }
}

For more information on facingMode, please see the MDN web docs https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints/facingMode

Show all cameras by deviceId

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>
            <Webcam audio={false} videoConstraints={{ deviceId: device.deviceId }} />
            {device.label || `Device ${key + 1}`}
          </div>

        ))}
    </>
  );
};

Recording a stream

https://codepen.io/mozmorris/pen/yLYKzyp?editors=0011

Using within an iframe

The Webcam component will fail to load when used inside a cross-origin iframe in newer version of Chrome (> 64). In order to overcome this security restriction a special allow attribute needs to be added to the iframe tag specifying microphone and camera as the required permissions like in the below example:

<iframe src="https://my-website.com/page-with-webcam" allow="camera; microphone;"/>

Mirrored video but non-mirrored screenshot

Add mirrored prop to the component will make the video and the screenshot be mirrored, but sometimes you need to show a mirrored video but take a non-mirrored screenshot, to accomplish that, you just need to add this CSS to your project:

video {
  transform: scaleX(-1);
}

You can find an example at https://codepen.io/mozmorris/pen/oNygXwz?editors=0110.

License

MIT

@pubngo-stack/platform-browser@borderfreefinancial/revo-consumer@borderfreefinancial/revo-core@borderfreefinancial/revo-core-api@borderfreefinancial/revo-web-video-test@transferwise/dynamic-flowsreact-ui-components-libconnect-react-components-libreact-mindeemindee-sdk-reactface-app-testfixsitbyevolution@mindee/react-web-essentialsfrontend-ui-kitnfg-frontend-ui-kitjp-ui-kitjpms-ui-kitcustomizable-react-uireact-sdk-devvideo-recorder-custompeer-genius-client@jackk5/ekyc-sdkweb-sdk-new-2web-sdk-webpacktest-packages123@shareid/authenticate_desktop@infinitebrahmanuniverse/nolb-react-werharuow-adminface-captcha@everything-registry/sub-chunk-2623enjoyselfiewebsdkpluginwhjr-quiz-sdkweb-ui-depswebcam-gs-1webcam-photowebmuitonote-ca-reactui-kit-narcello@experium/findy-form@experium/jobot-form@faceki/react-kyc-sdkut-portalv5gl-form-buildervishwam-hdb-react-sdkvishwam-poslite-react-sdkvishwam-react-ent-sdkvishwam-react-sdkvishwam-react-sdk-a8vishwam-react-video-sdkvishwam-rrfl-sdkvishwam-sdk-decentrovishwam-sdk-rrflvishwam-doc-masking-sdkvideo-recorder-itsaazvideo-recorder-personaltryon-component@hey-mirror/base@holism/form-generatorfindingpi-react-componentscitydi-bpms-sdkoaas_eko_dummyoaaseko@daym3l/react-profile-image@davi-ai/retorik-frameworkdbrain-camera-web-appproctoring_reactdocu-booth-packageqhc_job_uiq3-ui-docscandoris-camerareact-use-face-detectionreact_proctoring_libraryreact-tfjs-modelsreactfire-white-boardreact-three-mindreact-webcam-barcode-scannerreact-webcam-barcode-scanner2react-signy-form-component-test-1react-signy-form-component-test-2risingstar_newlaunchpad_microfrontendreact-qr-barcode-scannerreact-qr-barcode-scanner-17react-qr-barcode-scanner-18react-qr-barcode-scanner-esm5react-qr-barcode-scanner-forkreact-qr-barcode-scanner-recent-reactreact-qr-barcode-scanner-updatedreact-qrcode-readerreact-referential-formsreact-sprie-sdksimilar-passbaseshipfinex-kyc-formssinobest-rc-image-editsinobest-rc-image-edit-testsmarteye-protectsonic-widgetsonic-widget-apixspace-ui-core-framework
7.2.0

6 months ago

7.1.1

11 months ago

7.1.0

11 months ago

7.0.0

2 years ago

7.0.1

2 years ago

6.0.1

2 years ago

6.0.0

3 years ago

5.2.4-0

3 years ago

5.2.4

3 years ago

5.2.3

3 years ago

5.2.2

3 years ago

5.2.1

4 years ago

5.2.0

4 years ago

5.1.0

4 years ago

5.0.2

4 years ago

5.0.1

4 years ago

5.0.0

4 years ago

4.2.0

4 years ago

4.1.1

4 years ago

4.1.0

4 years ago

4.0.3

4 years ago

4.0.2

4 years ago

4.0.1

4 years ago

4.0.0

4 years ago

4.0.0-beta.1

5 years ago

4.0.0-beta.0

5 years ago

3.1.1

5 years ago

3.1.0

5 years ago

3.0.2

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

3.0.0-beta.0

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.1.1

5 years ago

1.1.0

5 years ago

1.0.4

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.7.0

6 years ago

0.6.0

6 years ago

0.5.0

6 years ago

0.4.3

6 years ago

0.4.2

6 years ago

0.4.1

6 years ago

0.4.0

6 years ago

0.3.1

6 years ago

0.3.0

6 years ago

0.2.0

7 years ago

0.1.0

7 years ago

0.0.14

8 years ago

0.0.13

8 years ago

0.0.12

8 years ago

0.0.11

8 years ago

0.0.10

8 years ago

0.0.9

8 years ago

0.0.8

8 years ago

0.0.7

9 years ago

0.0.6

9 years ago

0.0.5

9 years ago

0.0.4

9 years ago

0.0.3

9 years ago

0.0.2

9 years ago

0.0.1

9 years ago