Welcome folks today in this blog post we will be taking photo from webcam
in react.js using react-html5-camera-photo
library in browser using javascript. All the full source code
of the application is shown below.
Get Started
In order to get started you need to make a new react.js
app using the below command as shown below
npx create-react-app sampleapp
cd sampleapp
And after that you need to install the below library
using the below command as shown below
npm i react-html5-camera-photo
And after that you will see the below directory
structure of the react.js app as shown below
Taking Photo Using Webcam and Display it in Browser
Now we can modify the App.js
file and copy paste the following code
App.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import React, { useState } from "react"; import Camera from "react-html5-camera-photo"; import "react-html5-camera-photo/build/css/index.css"; export default function App(props) { const [uri, setUri] = useState(null); function handleTakePhoto(dataUri) { // Do stuff with the photo... console.log("takePhoto"); setUri(dataUri) } return ( <div> <Camera onTakePhoto={(dataUri) => { handleTakePhoto(dataUri); }} /> {uri && ( <img style={{ width: "500px",height: "200px" }} src={uri} /> )} </div> ); } |
As you can see we are importing the react-html5-camera-photo
library at the top and then we are embedding the component
and then we are passing the callback
function where we are calling
the function where the base64
code of the image will be returned and then we need to display that image inside the img
tag. And for that we are using the react.js useState
hook to store the dataUri
of the photo. And then we are displaying it inside the img
tag.