Giter Club home page Giter Club logo

react-webcam's Introduction

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

prop type default notes
audio boolean false enable/disable audio
audioConstraints object MediaStreamConstraint(s) for the audio
disablePictureInPicture boolean false disable Picture-in-Picture
forceScreenshotSourceSize boolean false uses size of underlying source video stream (and thus ignores other size related props)
imageSmoothing boolean true pixel smoothing of the screenshot taken
mirrored boolean false show camera preview and get the screenshot mirrored
minScreenshotHeight number min height of screenshot
minScreenshotWidth number min width of screenshot
onUserMedia function noop callback for when component receives a media stream
onUserMediaError function noop callback for when component can't receive a media stream with MediaStreamError param
screenshotFormat string 'image/webp' format of screenshot
screenshotQuality number 0.92 quality of screenshot(0 to 1)
videoConstraints object MediaStreamConstraints(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 possible 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

react-webcam's People

Contributors

amirabrams avatar amwam avatar cezary avatar clkao avatar daniel-cotton avatar dependabot[bot] avatar hedinne avatar hpaul avatar jeffersonfilho avatar jpserra avatar k-yle avatar krolow avatar lowewenzel avatar lucassaid avatar luispuig avatar mansya avatar mattstrick avatar megos avatar mozmorris avatar mwarnerdotme avatar npmcdn-to-unpkg-bot avatar opapirnyk avatar prashoon123 avatar psychiquest avatar steverob avatar timhwang21 avatar uwolfer avatar valerio-seb avatar wendellliu avatar ziahamza avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-webcam's Issues

Webcam issues on Chrome for android

First of all, great library. Kudos to that. I used it in a project. But on Chrome for android, I have come across this issue. After giving the permission to the camera. It is opening the mobile camera sometimes and sometimes it is not. If you want you can have a look at the simple solution I have built.

https://cameria.herokuapp.com

Help in resolving this issue would be super awesome.

Does not work in firefox

Developer Preview 41.0a2 (2015-07-31)

Error: TypeError: MediaStreamTrack.getSources is not a function

Package in npm registry out-of-date?

Installing this package via npm install react-webcam seems to pull down an old version of the package.

Seems like it needs a version bump and an npm publish?

Better error hint

I spent a few hours to understand why this component was not requesting for permissions to access the webcam, to find out that in Chrome, you can't request for the webcam if the site is not secure.

Error returned by onUserMediaError:

DOMException: Only secure origins are allowed (see: https://goo.gl/Y0ZkNV).

Find out more here: https://www.chromium.org/Home/chromium-security/prefer-secure-origins-for-powerful-new-features

Maybe a big hint should be added in the README.md and throw the error anyway, without calling onUserMediaError.

How to convert image from webcam to URL?

Hello! I am new in React Js. Can You help me? I want to create face recognition web app. And should to sent image from webcam to API Service. I need to sent image data in URL Format. How can I do It?

This is my solution:

var binaryData = [];
binaryData.push(this.state.screenshot);
const src = window.URL.createObjectURL(new Blob(binaryData, {type: "image/jpeg"}))

axios({
  method: 'post',
  url: 'https://eastasia.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false',
  headers:{'Ocp-Apim-Subscription-Key': 'Key'},
  data: {
    url: src
  }
}).then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });;

But I have error message:
code: "InvalidURL", message: "Invalid image URL."

Thank You!

Needs a maintainer

Hello,

Unfortunately I haven't had the time to maintain this project. Rather than let it stagnate and potentially break projects I'd be more than happy to transfer github and npm ownership over to anyone interested.

Capture video vs picture

Hi @mozmorris, wondering if there is a way to record video from the webcam using the library? The only option I can find is getSnapshot. If not, is that something you'd consider on your radar?

Thank you!

Multiple webcams support

Is it possible if I have multiple webcams connected to have multiple Webcam tags, each showing a different webcam? I see the enumerate devices where I could specify the audioSource and videoSource for each one.

react-webcam not working for remote ip

Hi,

i am using react-webcam in my application. My application running in server. i can access that application in local but the problem is webcam is not allowing if i access that application from local web browser.

webcam is working if i run that same application in my local machine. not working for server.

Please help me to sort out this issue.

Dependency error - factoryWithThrowingShims

I tried to use your module, but I received the following error:

error: Resolving deps of node_modules/react-webcam/dist/react-webcam.js failed. Could not load module './factoryWithThrowingShims'

After some digging, I found someone else with a similar issue.

The solution is to update the webpack config and include prop-types in the externals.

externals: [{
    react: {
      root: 'React',
      commonjs2: 'react',
      commonjs: 'react',
      amd: 'react'
    },
    "react-dom": {
      root: 'ReactDOM',
      commonjs2: 'react-dom',
      commonjs: 'react-dom',
      amd: 'react-dom'
    },
    "prop-types": {
      root: 'PropTypes',
      commonjs2: 'prop-types',
      commonjs: 'prop-types',
      amd: 'prop-types',
    }
  }],

I cloned your repo and tested it locally and it worked. Do you think you could add this in?

Doesn't work with iOS 11

Hey! Using this component works on Android, however isn't working on iOS 11 Safari. it correctly asks for access to the camera, however I get a Type Error:

screenshot 2017-09-28 10 18 14

Any ideas? Thanks!

navigator.mediaDevices.getUserMedia

The navigator.getUserMedia is not the standard for most browsers. Please use the navigator.mediaDevices.getUserMedia to support most of browsers.

Incompatible with Atom editor

I installed this package to use with my atom editor and it worked once, but now it crashes every single time. Uninstalling the package helped fix this problem. :(

Constraint Settings

Currently, the the options for width/height only affect the rendered canvas, not the video source though. there is no way to set it in the constraints, same goes for other constraints (like echo cancellation, etc...)

src attribute is not getting appended.

I am trying to use 'react-webcam' module and used simple code for it like
<Webcam className="webcam" ref='webcam' />

In local machine(MAC) it is working fine and got video tag as
<video autoplay="" width="640" height="480" class="webcam" data-reactid=".0.0.0.0.0.1.2" src="blob:http://localhost:5000/e655e4c2-feb1-47ca-8a3e-f5c354b37a0d"></video>

But when I am trying in my server(ubunthu) src attribute is not getting appended, getting plain video tag
<video autoplay="" width="640" height="480" class="webcam" data-reactid=".0.0.0.0.0.1.2"></video>

Please guide me where it is going wrong...

Thanks in advance...

If webcam is inside a modal, and the modal is closed soon after the modal is opened, the webcam does not stop

Hello,

Thanks for the wrapper, it worked really well for our purpose.

We have, however, found a small inconsistency. If we put the webcam inside a modal, and for whatever reason we close the Modal before the camera had the time to initialise, the camera stays 'on'. Almost in a locked state. If we try to open the Modal again, the camera does not show, because it is busy already with another process (I can tell that because Chrome shows a 'recording' icon on the tab and also the camera stays with the light on as if it was working). The only alternative is to refresh the browser.

Is there any method that we can plug to a callback to shut the webcam down?

Many thanks

image Filter

The image filter is applied using css only which makes it difficult to save or download the image with its corresponding filter.

Capture Video

I want to capture a video from the webcam and sent the file to aws s3.
Can I do this with this component and how would you suggest I go about this?

MediaStream.stop() is deprecated

Firefox 56.0 (64-bit) gives this "MediaStream.stop() is deprecated and will soon be removed. Use MediaStreamTrack.stop() instead."
Version 62.0.3202.62 (Official Build) (64-bit) is not warning anyting.

Not working on mobile browsers

Hi @mozmorris, thank you for putting out this library! I was unable to get the demo to work on mobile browsers. It seems like that might be because the origin is considered insecure (since the HTTPS certificate has expired)?

Should it be working on mobile browsers?

"Unhandled promise rejection" on Safari 11

On Safari 11 (Mac OS X High Sierra) webcam does not show up and this error displays in console:

[Error] Unhandled Promise Rejection: TypeError: Type error
	createObjectURL (bundle.js:104017)
	handleUserMedia (bundle.js:104017)
	(anonymous function) (bundle.js:103957)
	promiseReactionJob

Debugger shows this file as the source of Unhandled Promise Rejection: TypeError:

var src = window.URL.createObjectURL(stream);

React v0.14 support

With React v0.14, there's now this console message:

Warning: React.findDOMNode is deprecated. Please use ReactDOM.findDOMNode from require('react-dom') instead.

Not a big deal, but I just wanted to document it.

this.stream.stop is not a function

In latest Chrome I've got this error "this.stream.stop is not a function" when I'm trieng to make capture with "getScreenshot" function.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.