67 lines
2.6 KiB
JavaScript
67 lines
2.6 KiB
JavaScript
import { decode, grayOf } from "/static/js/ringcode.js";
|
||
|
||
const $ = (id) => document.getElementById(id);
|
||
const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true });
|
||
let engine, running = false, frames = 0, qr = 0, ring = 0, t0 = 0, fpsT = performance.now(), fpsN = 0;
|
||
let tokens = new Set(), mode = "aucun";
|
||
const history = [];
|
||
|
||
function reset() {
|
||
tokens = new Set(); t0 = performance.now(); frames = qr = ring = 0;
|
||
$("state").textContent = "Visez l'écran";
|
||
}
|
||
|
||
async function start() {
|
||
engine = await QrScanner.createQrEngine();
|
||
const stream = await navigator.mediaDevices.getUserMedia({
|
||
video: { facingMode: { ideal: "environment" }, width: { ideal: 1920 }, height: { ideal: 1080 } },
|
||
});
|
||
video.srcObject = stream;
|
||
await video.play();
|
||
running = true;
|
||
reset();
|
||
loop();
|
||
}
|
||
|
||
async function loop() {
|
||
if (!running) return;
|
||
if (video.readyState >= 2) {
|
||
const k = Math.min(1, 1280 / video.videoWidth);
|
||
canvas.width = Math.round(video.videoWidth * k);
|
||
canvas.height = Math.round(video.videoHeight * k);
|
||
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
||
frames++; fpsN++;
|
||
let res = null;
|
||
try { res = await QrScanner.scanImage(canvas, { qrEngine: engine, returnDetailedScanResult: true }); } catch { /* none */ }
|
||
if (res) {
|
||
qr++;
|
||
if (res.data.includes("#")) {
|
||
mode = "QR classique";
|
||
tokens.add(res.data.split("#")[1]);
|
||
} else {
|
||
mode = "anneaux";
|
||
const d = decode(grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height)), res.cornerPoints);
|
||
if (d && d.token) { ring++; tokens.add(d.token); }
|
||
}
|
||
}
|
||
if (tokens.size >= 5 && t0) {
|
||
const s = (performance.now() - t0) / 1000;
|
||
history.push(s.toFixed(1));
|
||
$("state").textContent = `5 codes en ${s.toFixed(1)} s`;
|
||
$("hist").textContent = `Essais : ${history.join(" s, ")} s`;
|
||
t0 = 0;
|
||
}
|
||
const now = performance.now();
|
||
if (now - fpsT > 1000) { $("fps").textContent = (fpsN * 1000 / (now - fpsT)).toFixed(1); fpsT = now; fpsN = 0; }
|
||
$("frames").textContent = frames;
|
||
$("qr").textContent = `${Math.round((100 * qr) / Math.max(1, frames))} %`;
|
||
$("ring").textContent = mode === "anneaux" ? `${Math.round((100 * ring) / Math.max(1, qr))} %` : "–";
|
||
$("count").textContent = `${Math.min(tokens.size, 5)} / 5`;
|
||
$("mode").textContent = mode;
|
||
}
|
||
setTimeout(loop, 0);
|
||
}
|
||
|
||
$("go").addEventListener("click", () => start().catch((e) => { $("state").textContent = `Caméra : ${e.message}`; }));
|
||
$("again").addEventListener("click", reset);
|