npm i bootstrap
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 71 72 |
import React, { useEffect, useRef } from "react"; import "bootstrap/dist/css/bootstrap.min.css"; 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; |