detection-lib
A modular JavaScript detection library for face, QR, and future detection types with a clean, unified API.
Features
- Pluggable Detectors — Start with face detection and extend easily with QR, object, etc.(currently only have face).
- Unified Interface — Every detector implements the same async
detect(input)
method.
- Factory Pattern — Use
createDetector({ type })
to initialize the correct implementation.
- Works in Browser — Supports
<video>
, <canvas>
, and <img>
HTML elements.
Installation
This library currently runs in the browser using ES modules.
Installation
npm install detection-lib
Usage
import { useEffect, useRef, useState } from 'react';
import { createDetector } from 'detection-lib';
// Create references and state
const detectorRef = useRef(null);
const [detectorCreated, setDetectorCreated] = useState(false);
const [detectorReady, setDetectorReady] = useState(false);
// Step 1: Create the detector when component mounts
useEffect(() => {
const create = async () => {
const detector = await createDetector({ type: 'face' });
detectorRef.current = detector;
setDetectorCreated(true);
};
create();
// Cleanup on unmount
return () => {
setDetectorCreated(false);
detectorRef.current = null;
};
}, []);
// Step 2: Initialize the detector once created
useEffect(() => {
const initialize = async () => {
if (detectorCreated && detectorRef.current) {
await detectorRef.current.initialize();
setDetectorReady(true);
}
};
initialize();
// Cleanup
return () => setDetectorReady(false);
}, [detectorCreated]);
// Step 3: Run detection (call this function after detector is ready)
const runDetection = async (input) => {
if (detectorReady && detectorRef.current) {
const result = await detectorRef.current.detect(input);
if (result.type === 'face' && result.boxes) {
result.boxes.forEach((box) => {
// Example: Draw box or process coordinates
console.log('Detected Face Box:', box);
});
}
}
};
API
createDetector(options)
- options.type: 'face' | 'qr' | string — The type of detector to create.
- Returns a detector instance with an async detect(input) method
Detector Interface
All detectors implement:
async detect(input: HTMLVideoElement | HTMLImageElement | HTMLCanvasElement): Promise<DetectionResult>
DetectionResult
- type: string — The detector type ('face', 'qr', etc.)
- boxes: Array of { x, y, w, h, score? } (for face, etc.)
- data: Any extra data (for QR, etc.)
Extending
To add a new detector:
1. Create a new file in src/detectors/ (e.g., myDetector.js).
2. Implement a class with a detect() method.
3. Register it in the factory in src/DetectorFactory.js.