Skip to content

Repository files navigation

react-webcam

Build Statusdownloads

Webcam component for React. See this for browser compatibility.

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

Installation

npm install react-webcam

Demo

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

Usage

importReactfrom"react";importWebcamfrom"react-webcam";constWebcamComponent=()=><Webcam/>;

Props

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

proptypedefaultnotes
audiobooleantrueenable/disable audio
audioConstraintsobjectMediaStreamConstraint(s) for the audio
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:

CodePen demo

constvideoConstraints={width: 1280,height: 720,facingMode: "user"};constWebcamCapture=()=>{constwebcamRef=React.useRef(null);constcapture=React.useCallback(()=>{constimageSrc=webcamRef.current.getScreenshot();},[webcamRef]);return(<><Webcamaudio={false}height={720}ref={webcamRef}screenshotFormat="image/jpeg"width={1280}videoConstraints={videoConstraints}/><buttononClick={capture}>Capture photo</button></>);};

Choosing a camera

User/Selfie/forward facing camera

classWebcamCaptureextendsReact.Component{render(){constvideoConstraints={facingMode: "user"};return<WebcamvideoConstraints={videoConstraints}/>;}}

Environment/Facing-Out camera

classWebcamCaptureextendsReact.Component{render(){constvideoConstraints={facingMode: {exact: "environment"}};return<WebcamvideoConstraints={videoConstraints}/>;}}

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

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;"/>

License

MIT

About

Webcam component

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages