Welcome folks today in this blog post we will be taking selfie picture
and display it inside browser using webcam
and useEffect
and useRef
hooks in 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
project using the below command
npx create-react-app sampleapp
And now you will be seeing the below directory
structure of the react.js app
And now we need to make 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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
import React, { useEffect, useRef } from "react"; function App() { let videoRef = useRef(null); let photoRef = useRef(null) const getVideo = () => { navigator.mediaDevices .getUserMedia({ video: true }) .then((stream) => { let video = videoRef.current; video.srcObject = stream; video.play(); }) .catch((err) => { console.error(err); }); }; const takePicture = () => { const width = 400 const height = width / (16 / 9) let video = videoRef.current let photo = photoRef.current photo.width = width photo.height = height let ctx = photo.getContext('2d') ctx.drawImage(video, 0, 0, width, height) } const clearImage = () => { let photo = photoRef.current let ctx = photo.getContext('2d') ctx.clearRect(0,0,photo.width,photo.height) } useEffect(() => { getVideo(); }, [videoRef]); return ( <div className="container"> <h1 className="text-center">Camera Selfie App in React</h1> <video ref={videoRef} className="container"></video> <button onClick={takePicture} className="btn btn-danger container">Take Picture</button> <canvas className="container" ref={photoRef}></canvas> <button onClick={clearImage} className="btn btn-primary container">Clear Image</button> <br/><br/> </div> ); } export default App; |
As you can see we are using the useRef
and useEffect
hooks and then inside the html we have two buttons in which we allow the user to take
the snapshot and clear the image. And then we have the section
where we are showing the live user
webcam as shown below