Skip to content

Instantly share code, notes, and snippets.

@wesbos
Created May 31, 2022 19:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wesbos/50ec1bace2ec0f5cbe3a959dc099b152 to your computer and use it in GitHub Desktop.
Save wesbos/50ec1bace2ec0f5cbe3a959dc099b152 to your computer and use it in GitHub Desktop.
import { codes } from './database';
const app = document.querySelector('.app') as HTMLDivElement;
const videoEl = app.querySelector('video');
const canvasEl = app.querySelector('canvas');
const labelsEl = app.querySelector('.labels') as HTMLDivElement;
const ctx = canvasEl.getContext('2d');
interface Window {
BarcodeDetector: any;
}
export interface BoundingBox {
x: number;
y: number;
width: number;
height: number;
top: number;
right: number;
bottom: number;
left: number;
}
export interface CornerPoint {
x: number;
y: number;
}
export interface DetectedBarcode {
boundingBox: BoundingBox;
cornerPoints: CornerPoint[];
format: string;
rawValue: string;
}
const barcodeDetector = new window.BarcodeDetector({ formats: ['data_matrix', 'aztec', 'qr_code'] });
async function populateVideo() {
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false }).catch(console.error);
console.log(stream)
if(!stream) return;
videoEl.srcObject = stream;
videoEl.muted = true;
await videoEl.play();
canvasEl.width = videoEl.videoWidth / 4;
canvasEl.height = videoEl.videoHeight / 4;
setInterval(detectBarcodes, 200);
setInterval(paintToCanvas, 20);
}
function paintToCanvas() {
ctx.drawImage(videoEl, 0, 0, canvasEl.width, canvasEl.height);
}
async function detectBarcodes() {
const results: DetectedBarcode[] = await barcodeDetector.detect(videoEl);
results.forEach(result => {
console.log('Detected barcode', result.rawValue);
console.table(result.cornerPoints);
console.table(result.boundingBox);
const { x, y, width, height } = result.boundingBox;
console.log(result.cornerPoints);
// select the label for this element
const label = labelsEl.querySelector(`[data-code="${result.rawValue}"]`) as HTMLSpanElement;
label.style.width = `${width}px`;
label.style.height = `${height}px`;
label.style.left = `${x}px`;
label.style.top = `${y}px`;
// ctx.strokeStyle = 'red';
// ctx.strokeRect(x, y, width, height);
})
}
async function createLabels() {
Object.values(codes).forEach(code => {
const el = document.createElement('span');
el.classList.add('label');
el.innerText = code.name;
el.dataset.code = code.value.toString();
labelsEl.appendChild(el);
});
}
populateVideo();
createLabels();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment