'use client'; import { useEffect, useRef, useState } from 'react'; import Webcam from 'react-webcam'; import { Button, message } from 'antd'; import { loadFaceApi } from '@/utils/loadFaceApi'; export default function CameraComponent({ onCapture }) { const webcamRef = useRef(null); const canvasRef = useRef(null); const [faceDetected, setFaceDetected] = useState(false); const [imageSrc, setImageSrc] = useState(null); const [messageApi, contextHolder] = message.useMessage(); const intervalRef = useRef(null); useEffect(() => { initFaceDetection(); return () => { if (intervalRef.current) clearInterval(intervalRef.current); }; }, []); const initFaceDetection = async () => { const faceapi = await loadFaceApi(); intervalRef.current = setInterval(async () => { if ( webcamRef.current && webcamRef.current.video && webcamRef.current.video.readyState === 4 ) { const video = webcamRef.current.video; const canvas = canvasRef.current; const ctx = canvas.getContext('2d'); const displaySize = { width: video.videoWidth, height: video.videoHeight, }; // Samakan ukuran canvas dengan video canvas.width = displaySize.width; canvas.height = displaySize.height; const detections = await faceapi.detectAllFaces( video, new faceapi.TinyFaceDetectorOptions({ inputSize: 416, scoreThreshold: 0.5, }) ); setFaceDetected(detections.length > 0); const resized = faceapi.resizeResults(detections, displaySize); // Gambar bounding box mirror ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.save(); ctx.scale(-1, 1); ctx.translate(-canvas.width, 0); faceapi.draw.drawDetections(canvas, resized); ctx.restore(); } }, 400); }; const capture = () => { const screenshot = webcamRef.current.getScreenshot(); setImageSrc(screenshot); onCapture(screenshot); }; const reset = () => { setImageSrc(null); onCapture(null); }; return (
{contextHolder} {!imageSrc ? ( <>
{faceDetected ? ( Wajah terdeteksi ✅ ) : ( Arahkan wajah ke kamera ❌ )}
) : ( <> Foto )}
); }