import { Camera, RotateCcw, X } from 'lucide-react'; import { useCallback, useEffect, useRef, useState } from 'react'; import { Button } from '@/components/ui/button'; interface CameraCaptureProps { onCapture: (dataUrl: string) => void; onClose: () => void; } export function CameraCapture({ onCapture, onClose }: CameraCaptureProps) { const videoRef = useRef(null); const canvasRef = useRef(null); const [stream, setStream] = useState(null); const [capturedImage, setCapturedImage] = useState(null); const [error, setError] = useState(null); const startCamera = useCallback(async () => { try { const mediaStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user', width: 640, height: 480 }, }); setStream(mediaStream); if (videoRef.current) { videoRef.current.srcObject = mediaStream; } setError(null); } catch { setError( 'Tidak dapat mengakses kamera. Pastikan izin kamera diberikan.', ); } }, []); useEffect(() => { startCamera(); return () => { stream?.getTracks().forEach((track) => track.stop()); }; }, []); const capture = () => { if (!videoRef.current || !canvasRef.current) { return; } const canvas = canvasRef.current; const video = videoRef.current; canvas.width = video.videoWidth; canvas.height = video.videoHeight; const ctx = canvas.getContext('2d'); if (!ctx) { return; } ctx.translate(canvas.width, 0); ctx.scale(-1, 1); ctx.drawImage(video, 0, 0); ctx.setTransform(1, 0, 0, 1, 0, 0); const dataUrl = canvas.toDataURL('image/jpeg', 0.8); setCapturedImage(dataUrl); stream?.getTracks().forEach((track) => track.stop()); }; const retake = () => { setCapturedImage(null); startCamera(); }; const confirm = () => { if (capturedImage) { onCapture(capturedImage); } }; return (

Ambil Foto

{error ? (

{error}

) : capturedImage ? (
Captured
) : (
)}
); }