-
-
Save Desttro/5bac8544ffe58cf7e18a80d9c8b7ead8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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