Using react-webcam to take selfies in your ReactJS project
Hereās what the final project looks like:
step 1: Create a react project
npx create-react-app webcam-selfie
step 2: install the dependencies
yarn add react-webcam
for styling (ignore if youāre not using MUI):To install and save in yourĀ
package.json
Ā dependencies, run the command below usingĀ npm:npm install @mui/material @emotion/react @emotion/styled
OrĀ yarn:
yarn add @mui/material @emotion/react @emotion/styled
Material UI is usingĀ emotionĀ as a styling engine by default. If you want to useĀ
styled-components
Ā instead, run:npm install @mui/material @mui/styled-engine-sc styled-components
yarn add @mui/material @mui/styled-engine-sc styled-components
for using mui icons:
npm install @mui/icons-material
Ā
step 3: make your components!
App.js
import "./App.css";
import { Navbar } from "./Navbar";
import { WebcamComponent } from "./WebcamComponent";
function App() {
return (
<div className="App">
<WebcamComponent />
</div>
);
}
export default App;
Ā
WebcamComponent.js
import * as Reactfrom "react";
import Webcam from "react-webcam";
import { useCallback, useRef, useState } from "react";
import CameraAltIconfrom "@mui/icons-material/CameraAlt";
import Gridfrom "@mui/material/Grid";
import ReplayIconfrom "@mui/icons-material/Replay";
export const WebcamComponent = () => { const videoConstraints = { width: "100%", height: "100%", facingMode: "user", // facingMode: { exact: "environment" } }; // creating webcam reference const webcamRef = useRef(null); // imgSrc stores the image const [imgSrc, setImgSrc] = useState(null); // variable that controls if the camera is open or not const [startCam, setStartCam] = useState(false); const onCapture = useCallback(() => { const imageSrc = webcamRef.current.getScreenshot(); setImgSrc(imageSrc); }, [webcamRef]); const usePhoto = () => { if (imgSrc) { //store image in firebase - code below! setImgSrc(null); } }; const startCamera = () => { setStartCam(true); }; const stopCamera = () => { setStartCam(false); setImgSrc(null); }; }
// this is a random image from Unsplash
const exampleImage =
"https://images.unsplash.com/photo-1529650604660-cec743ea7788?ixlib=rb-1.2.1&raw_url=true&q=80&fm=jpg&crop=entropy&cs=tinysrgb&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2340";
return ( <div style={{ alignSelf: "center", paddingHorizontal: "20%", fontFamily: "monospace", fontSize: 20, fontWeight: "bold", letterSpacing: "2px", backgroundColor: "#020202", paddingBottom: "10%", }} > {startCam ? ( <> {imgSrc ? ( <> <img alt="clicked from webcam" src={imgSrc} /> <Grid container direction="row" justifyContent="center"> <Grid onClick={() => { setImgSrc(null); }} item sx={{ borderRadius: "1.33rem", paddingTop: "10%", alignItems: "center", padding: "1.25rem", }} > <ReplayIcon sx={{ fontSize: 25, color: "#fff" }} /> </Grid> <Grid sx={{ width: "40%", backgroundColor: "#fd0159", borderRadius: "1.33rem", paddingTop: "10%", alignItems: "center", padding: "1.25rem", }} onClick={usePhoto} item > <div style={{ color: "#fff", fontSize: 18, marginLeft: 5, textAlign: "center", }} > Save Image </div> </Grid> </Grid> <div style={{ width: "80%", backgroundColor: "#feefe0", borderRadius: "1.33rem", alignItems: "center", padding: "2%", margin: "0 auto", marginTop: "5%", }} onClick={stopCamera} > <div style={{ color: "#000", fontSize: 20, marginLeft: 5, textAlign: "center", }} > Stop Camera </div> </div> </> ) : ( <div style={{ backgroundColor: "#020202", paddingBottom: "10%", }} > <Webcam audio={false} style={{ width: "80%", height: "70%", objectFit: "cover", borderRadius: 16, }} ref={webcamRef} screenshotFormat="image/jpeg" videoConstraints={videoConstraints} /> <div style={{ width: "80%", backgroundColor: "#fd0159", borderRadius: "1.33rem", alignItems: "center", padding: "2%", margin: "0 auto", }} onClick={onCapture} > <div style={{ color: "#fff", fontSize: 20, marginLeft: 5, textAlign: "center", }} > Capture </div> </div> <div style={{ width: "80%", backgroundColor: "#feefe0", borderRadius: "1.33rem", alignItems: "center", padding: "2%", margin: "0 auto", marginTop: "5%", }} onClick={stopCamera} > <div style={{ color: "#000", fontSize: 20, marginLeft: 5, textAlign: "center", }} > Stop Camera </div> </div> </div> )} </> ) : ( <> <img alt="neon pink smiley face" src={exampleImage} style={{ width: "80%", height: "70%", objectFit: "cover", borderRadius: 20, }} /> <Grid onClick={startCamera} container direction="row" justifyContent="center" sx={{ width: "80%", backgroundColor: "#fd0159", borderRadius: "1.33rem", paddingTop: "10%", alignItems: "center", padding: "1.25rem", margin: "0 auto", }} > <Grid item> <CameraAltIcon sx={{ fontSize: 25, color: "#fff" }} /> </Grid> <Grid item> <div style={{ color: "#fff", fontSize: 20, marginLeft: 5, textAlign: "center", }} > ģ“¬ģķźø° </div> </Grid> </Grid> </> )} </div> ); };
step 4: set up firebase storage to store your images!
install firebase:
npm install --save firebase
note firebase version:
"firebase": "^9.6.1",
firebase.js
// Import the functions you need from the SDKs you need // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries import { initializeApp } from "firebase/app"; import { getStorage } from 'firebase/storage' // Your web app's Firebase configuration const firebaseConfig = { apiKey: "your key", authDomain: "", projectId: "", storageBucket: "", messagingSenderId: "", appId: "", measurementId: "" }; // Initialize Firebase constapp= initializeApp(firebaseConfig); conststorage= getStorage(app); export {storage,app};
Ā
MAKE SURE TO REVISE FIREBASE STORAGE RULES ACCORDINGLY
rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /{allPaths=**} { allow read, write: if true; } } }
step 5: usage in WebcamComponent.js
import {storage} from "./firebase"; import { ref, uploadString } from "firebase/storage"; const imageFilename = "selfie"; const [counter, setCounter] = useState(0); const usePhoto = () => { if (imgSrc) { try { const storageRef = ref( storage, "sanscam/" + imageFilename + counter.toString() ); uploadString(storageRef, imgSrc, "data_url").then((snapshot) => { console.log("Uploaded a data_url string!"); }); } catch (e) { console.log(e); } setImgSrc(null); setCounter(counter + 1); } };
The images will be stored in firebase storage
Ā
Have a good week!
Ā
Ā