Spaces:
Sleeping
Sleeping
import React, { useEffect, useRef } from "react"; | |
interface VideoWrapperProps { | |
width?: string | number; | |
height?: string | number; | |
className?: string; | |
handleNextStep: () => void; // Function to handle the next step | |
setImage: (imageDataUrl: string) => void; // Function to set the image data URL | |
} | |
// VideoWrapper component | |
const VideoWrapper: React.FC<VideoWrapperProps> = ({ | |
width, | |
height, | |
className, | |
handleNextStep, | |
setImage, | |
}) => { | |
const videoRef = useRef<HTMLVideoElement | null>(null); | |
const canvasRef = useRef<HTMLCanvasElement | null>(null); | |
useEffect(() => { | |
const startCamera = async () => { | |
try { | |
const stream = await navigator.mediaDevices.getUserMedia({ | |
video: true, | |
}); | |
if (videoRef.current) { | |
videoRef.current.srcObject = stream; | |
} | |
} catch (error) { | |
console.error("Erreur lors de l'accès à la caméra :", error); | |
} | |
}; | |
startCamera(); | |
return () => { | |
if (videoRef.current) { | |
const stream = videoRef.current.srcObject as MediaStream; | |
if (stream) { | |
const tracks = stream.getTracks(); | |
tracks.forEach((track) => track.stop()); | |
} | |
} | |
}; | |
}, []); | |
const captureImage = async () => { | |
const canvas = canvasRef.current; | |
const video = videoRef.current; | |
if (canvas && video) { | |
const context = canvas.getContext("2d"); | |
if (context) { | |
canvas.width = video.videoWidth; // Width of the video | |
canvas.height = video.videoHeight; // Height of the video | |
context.drawImage(video, 0, 0, canvas.width, canvas.height); // Draw the video on the canvas | |
return canvas.toDataURL("image/png"); // Return the image as a Data URL | |
} | |
} | |
}; | |
return ( | |
<> | |
<div | |
className={`relative shadow-blue-200 ${className}`} | |
style={{ | |
width, | |
height, | |
backgroundColor: "black", | |
display: "flex", | |
justifyContent: "center", | |
alignItems: "center", | |
overflow: "hidden", | |
}} | |
> | |
<video | |
ref={videoRef} | |
autoPlay | |
muted | |
style={{ | |
display: "block", | |
width: "100%", | |
height: "100%", | |
objectFit: "cover", | |
}} | |
/> | |
<canvas ref={canvasRef} style={{ display: "none" }} />{" "} | |
{/* Hidden canvas */} | |
</div> | |
<button | |
onClick={async () => { | |
const imageDataUrl = await captureImage(); // Capture the image | |
setImage(imageDataUrl ?? ""); // Set the captured image | |
handleNextStep(); // Proceed to the next step | |
}} | |
className="bg-blue-600 transition text-white rounded-2xl text-xl hover:bg-gray-800 mt-32 w-40 h-16" | |
> | |
Continue | |
</button> | |
</> | |
); | |
}; | |
export default VideoWrapper; | |