Camera Access in React Js
Here's a complete example code for opening the camera in React JS using the getUserMedia API:
javascriptimport React, { useRef, useEffect } from "react";const Camera = () => {const videoRef = useRef(null);useEffect(() => {const constraints = { video: true };const openCamera = async () => {try {const stream = await navigator.mediaDevices.getUserMedia(constraints);videoRef.current.srcObject = stream;} catch (error) {console.error("Error opening camera", error);}};openCamera();}, []);return <video ref={videoRef} autoPlay />;};export default Camera;
In this code, we create a functional component called Camera that contains a video element with a ref attribute set to videoRef. We then use the useEffect hook to call the navigator.mediaDevices.getUserMedia method to request access to the camera. Once access is granted, the video stream is assigned to the srcObject property of the videoRef using the videoRef.current.srcObject = stream statement.
Finally, we return the video element with the autoPlay attribute set to true. This allows the video to start playing as soon as the camera stream is available.
Note that you'll need to grant camera access permission in your browser for this code to work. Additionally, this code is just a starting point and may need to be modified depending on your specific needs.
Comments
Post a Comment