react-webcam vs jslib-html5-camera-photo vs react-html5-camera-photo
Capturing Images from Webcams in React and Vanilla JS
react-webcamjslib-html5-camera-photoreact-html5-camera-photo

Capturing Images from Webcams in React and Vanilla JS

These three libraries enable developers to access user webcams and capture photos directly within web applications. react-webcam is a React component that provides direct access to the video stream and screenshot capabilities. react-html5-camera-photo is a React wrapper designed specifically for taking photos with built-in callbacks. jslib-html5-camera-photo is the underlying vanilla JavaScript library that powers the React wrapper, suitable for non-React projects or lower-level integration.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
react-webcam480,0301,750168 kB653 years agoMIT
jslib-html5-camera-photo37,40213897.4 kB9-MIT
react-html5-camera-photo30,662219246 kB15-MIT

Webcam Image Capture: react-webcam vs react-html5-camera-photo vs jslib-html5-camera-photo

Accessing a user's camera in a web application requires handling permissions, video streams, and canvas rendering. The packages react-webcam, react-html5-camera-photo, and jslib-html5-camera-photo all solve this problem but approach it from different angles. Let's compare how they handle core tasks like initialization, capturing images, and configuration.

📦 Core Architecture: Component vs Library

react-webcam is a pure React component.

  • It renders a <video> element internally.
  • You interact with it using React refs to trigger actions.
  • Best for standard React applications where you want to keep logic inside components.
// react-webcam: Component usage
import Webcam from "react-webcam";

function MyComponent() {
  const webcamRef = useRef(null);
  return <Webcam ref={webcamRef} />;
}

react-html5-camera-photo is also a React component but wraps specific capture logic.

  • It focuses on the "take photo" action as a primary event.
  • It uses callbacks to return the image data immediately upon capture.
  • Useful when the capture action is the main goal of the component.
// react-html5-camera-photo: Component usage
import Camera from "react-html5-camera-photo";

function MyComponent() {
  const handlePhoto = (dataUri) => console.log(dataUri);
  return <Camera onTakePhoto={handlePhoto} />;
}

jslib-html5-camera-photo is a vanilla JavaScript library.

  • It does not depend on React or any framework.
  • You must manually attach it to a DOM element (like a <video> tag).
  • Ideal for vanilla JS projects or when you need to avoid React overhead.
// jslib-html5-camera-photo: Vanilla JS usage
import { CameraPhoto } from "jslib-html5-camera-photo";

const cameraPhoto = new CameraPhoto("#video-element");
cameraPhoto.startCamera();

📸 Capturing Images: Manual Trigger vs Callback

The way you retrieve the image data differs significantly between these tools.

react-webcam requires you to call a method on the ref.

  • You decide exactly when the screenshot happens (e.g., on button click).
  • Returns a base64 string of the current video frame.
  • Gives you full control over timing.
// react-webcam: Manual capture
const takeShot = () => {
  const imageSrc = webcamRef.current.getScreenshot();
  console.log(imageSrc);
};

<button onClick={takeShot}>Capture</button>

react-html5-camera-photo uses a prop callback.

  • The component handles the capture logic internally.
  • You provide a function to receive the data URI automatically.
  • Less boilerplate but less control over the exact trigger moment.
// react-html5-camera-photo: Callback capture
const handlePhoto = (dataUri) => {
  console.log(dataUri);
};

<Camera onTakePhoto={handlePhoto} />;

jslib-html5-camera-photo uses a class method.

  • You call takePhoto() on the instance.
  • Returns a promise or data URI depending on configuration.
  • Requires manual DOM management alongside the logic.
// jslib-html5-camera-photo: Method capture
const photoData = cameraPhoto.takePhoto();
console.log(photoData);

⚙️ Configuration: Video Constraints and Settings

Configuring resolution, aspect ratio, and image format is critical for performance and quality.

react-webcam passes constraints directly to the video element.

  • Uses the standard videoConstraints prop.
  • Supports width, height, and facing mode (user/environment).
  • Aligns closely with native MediaStream constraints.
// react-webcam: Video constraints
<Webcam
  videoConstraints={{
    width: 1280,
    height: 720,
    facingMode: "user"
  }}
/>

react-html5-camera-photo uses specific props for image output.

  • Uses imageType to set format (jpg/png).
  • Uses resultType to define output (base64/uint8array).
  • Video constraints are passed similarly but focused on capture output.
// react-html5-camera-photo: Image settings
<Camera
  imageType="jpg"
  resultType="base64"
  idealResolution={{ width: 1280, height: 720 }}
/>

jslib-html5-camera-photo configures via constructor or methods.

  • You set options when initializing the class.
  • Provides low-level control over the canvas and stream.
  • Requires more setup code to achieve the same result.
// jslib-html5-camera-photo: Initialization options
const options = {
  width: 1280,
  height: 720,
  imageType: "jpg"
};
const cameraPhoto = new CameraPhoto("#video", options);

🛠️ Maintenance and Ecosystem Support

Long-term project health depends on library maintenance and community support.

react-webcam has consistent updates and wide adoption.

  • Actively maintained with regular fixes for React versions.
  • Large community means easier troubleshooting.
  • Safe choice for production enterprise applications.
// react-webcam: Standard import
import Webcam from "react-webcam";
// Widely supported in current React versions

react-html5-camera-photo has had periods of low activity.

  • Some users report issues with newer React strict mode.
  • Fewer contributors compared to react-webcam.
  • Use with caution in long-term projects without a fork strategy.
// react-html5-camera-photo: Potential compatibility check
import Camera from "react-html5-camera-photo";
// Verify React version compatibility before install

jslib-html5-camera-photo is stable but niche.

  • Updates depend on the core html5-camera-photo project.
  • Good for specific non-React use cases.
  • Less community support for React-specific integration issues.
// jslib-html5-camera-photo: Vanilla stability
import { CameraPhoto } from "jslib-html5-camera-photo";
// Stable API for vanilla JS contexts

📊 Summary: Key Differences

Featurereact-webcamreact-html5-camera-photojslib-html5-camera-photo
Framework⚛️ React⚛️ React🌐 Vanilla JS
Capture Method🖱️ Manual (ref method)🔄 Callback (prop)🖱️ Manual (class method)
Configuration🎛️ videoConstraints🎛️ imageType/resultType🎛️ Constructor options
Maintenance✅ Active⚠️ Less Active✅ Stable
Best Use🏢 General React Apps📸 Photo-First Components🛠️ Non-React Projects

💡 Final Recommendation

react-webcam is the standard choice for React developers.
It balances flexibility with stability and fits naturally into the React component model. Use it for dashboards, profile uploads, or any feature where webcam access is part of a larger interface.

react-html5-camera-photo works well for simple photo booths.
If your sole goal is to take a picture and you want the data handed to you automatically, this reduces boilerplate. Just ensure you test it thoroughly with your specific React version.

jslib-html5-camera-photo is for vanilla JavaScript needs.
Reach for this when you are not using React or need to integrate camera logic into a legacy codebase without framework dependencies. It provides the foundation that the React wrappers are built upon.

How to Choose: react-webcam vs jslib-html5-camera-photo vs react-html5-camera-photo

  • react-webcam:

    Choose react-webcam for most React projects requiring stable, long-term support and active maintenance. It offers a straightforward API to access the video stream and capture screenshots on demand. This package is ideal when you need flexibility to customize the video constraints and handle the capture action separately from the component rendering.

  • jslib-html5-camera-photo:

    Choose jslib-html5-camera-photo if you are building a vanilla JavaScript application or using a framework other than React. It provides direct access to the camera hardware without React-specific dependencies. This option gives you full control over the implementation but requires more boilerplate code to manage the video element and canvas rendering manually.

  • react-html5-camera-photo:

    Choose react-html5-camera-photo if you need a React component that handles the photo capture logic internally via callbacks. It simplifies the process by exposing an onTakePhoto prop instead of requiring manual screenshot triggers. However, verify compatibility with your React version, as maintenance has been less consistent compared to other options.

README for react-webcam

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