@face-detector/react-face-detection
Version:
Face Detector Web SDK React Components and Hooks Package
129 lines (104 loc) • 4.66 kB
Markdown
# @face-detector/react-face-detection
`@face-detector/react-face-detection`은 FaceDetection Web SDK v2를 React 환경에서 손쉽게 사용할 수 있도록 도와주는 React Hooks, 컴포넌트, 컨텍스트를 제공하는 패키지입니다.
## React 사용법 (`@face-detector/react-face-detection`)
### 5.1 기본 사용법 (통합 훅)
Provider+Video+Hook 조합 예시:
```tsx
import {
FaceDetectorProvider,
FaceDetectorVideo,
useFaceDetector,
useFaceDetectorState,
useProgress,
useCountDown,
useFacePosition,
ProcessState
} from '@face-detector/react-face-detection';
import { ReportProcessor } from '@face-detector/report-processor';
function App() {
const { start, stop, reset, terminate, report, duration, enableRGBExtraction } = useFaceDetector();
const state = useFaceDetectorState();
const progress = useProgress();
const countdown = useCountDown();
const facePosition = useFacePosition();
const handleDownloadResult = () => {
if (!report) return;
const processor = new ReportProcessor(report);
const downloadFunc = processor.createDownloadFunction('measurement_result.txt');
downloadFunc();
};
return (
<FaceDetectorProvider>
<FaceDetectorVideo style={{ width: 640, height: 480 }} />
<div>
<button disabled={state !== ProcessState.READY} onClick={() => start()}>Start</button>
<button disabled={state === ProcessState.READY} onClick={() => stop()}>Stop</button>
<button onClick={() => reset()}>Reset</button>
<button disabled={state !== ProcessState.RUNNING && state !== ProcessState.MEASURING} onClick={() => enableRGBExtraction(false)}>Pause Extraction</button>
<button disabled={state !== ProcessState.RUNNING} onClick={() => enableRGBExtraction(true)}>Resume Extraction</button>
<button
disabled={!report || state !== ProcessState.COMPLETED}
onClick={handleDownloadResult}
>
결과 저장
</button>
<div>상태: {state}</div>
<div>진행률: {progress}%</div>
<div>카운트다운: {countdown}</div>
<div>얼굴 감지: {facePosition ? '감지됨' : '감지되지 않음'}</div>
{duration && <div>측정 시간: {Math.round(duration)}ms</div>}
{report && (
<details>
<summary>측정 결과 보기</summary>
<pre>{JSON.stringify(report, null, 2)}</pre>
</details>
)}
</div>
</FaceDetectorProvider>
);
}
```
### 5.2 개별 훅 사용법
필요한 상태값만 선택적으로 사용할 수 있습니다:
```tsx
import {
useFaceDetector,
useProgress,
useCountDown,
useFacePosition
} from '@face-detector/react-face-detection';
// 메인 제어 훅
const { start, stop, reset, terminate, report, duration, detector, enableRGBExtraction } = useFaceDetector();
// 개별 상태 훅들
const state = useFaceDetectorState(); // "INITIALIZING" | "READY" | "RUNNING" | "MEASURING" | "COMPLETED" | "FAILED" | "CANCELED"
const progress = useProgress(); // 0-100 진행률
const countdown = useCountDown(); // 카운트다운 값
const facePosition = useFacePosition(); // 얼굴 위치 정보 또는 null
// RGB 추출 일시중지/재개
enableRGBExtraction(false);
enableRGBExtraction(true);
```
### 5.3 사용 가능한 메서드들
- `start()`: 측정 시작 (Promise<Report> 반환)
- `stop()`: 측정 중단
- `reset()`: 상태 초기화
- `terminate()`: 모든 리소스 해제 및 종료
- `enableRGBExtraction(shouldExcuteRGBExtraction: boolean)`: RGB 추출 일시중지/재개
### 5.4 콜백 및 고급 기능
FaceDetectorVideo는 style과 className props를 지원하며, Provider에서는 다양한 콜백을 제공합니다:
```tsx
<FaceDetectorProvider
onVideoReady={(video) => {/* 비디오 엘리먼트 획득 */}}
onCanvasReady={(extCanvas, valCanvas) => {/* 캔버스 획득 */}}
onStreamReady={(stream) => {/* MediaStream 관찰(읽기 전용) */}}
>
<FaceDetectorVideo style={{ width: 640, height: 480 }} />
</FaceDetectorProvider>
```
### 5.5 추가 기능
- **FaceDetectorVideo forwardRef 지원**: 외부에서 `<video>` DOM에 접근 가능
```tsx
const videoRef = useRef<HTMLVideoElement>(null);
<FaceDetectorVideo ref={videoRef} style={{ width: 640, height: 480 }} />
```
- **onStreamReady(stream)**: Provider가 `READY` 상태가 되면 내부 `video.srcObject`가 `MediaStream`인 경우 콜백으로 전달됩니다(읽기 전용 용도 권장).