feat: Kamera-Adapter mit Datei-Ersatzweg
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Startet den Kamerastrom in einem <video>-Element.
|
||||
* Bevorzugt die Ruecckamera und eine hohe Aufloesung, damit die
|
||||
* kleine Etikettenschrift lesbar bleibt.
|
||||
*/
|
||||
export async function startCamera(videoElement) {
|
||||
const stream = await navigator.mediaDevices.getUserMedia({
|
||||
video: {
|
||||
facingMode: { ideal: 'environment' },
|
||||
width: { ideal: 1920 },
|
||||
height: { ideal: 1080 },
|
||||
},
|
||||
audio: false,
|
||||
});
|
||||
|
||||
videoElement.srcObject = stream;
|
||||
videoElement.setAttribute('playsinline', '');
|
||||
await videoElement.play();
|
||||
|
||||
return {
|
||||
stop() {
|
||||
for (const track of stream.getTracks()) track.stop();
|
||||
videoElement.srcObject = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function drawScaled(source, sourceWidth, sourceHeight, maxEdge) {
|
||||
const scale = Math.min(1, maxEdge / Math.max(sourceWidth, sourceHeight));
|
||||
const width = Math.round(sourceWidth * scale);
|
||||
const height = Math.round(sourceHeight * scale);
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const context = canvas.getContext('2d', { willReadFrequently: true });
|
||||
context.drawImage(source, 0, 0, width, height);
|
||||
return context.getImageData(0, 0, width, height);
|
||||
}
|
||||
|
||||
/** Einzelbild aus dem laufenden Kamerastrom. */
|
||||
export function grabFrame(videoElement, maxEdge = 1280) {
|
||||
return drawScaled(
|
||||
videoElement,
|
||||
videoElement.videoWidth,
|
||||
videoElement.videoHeight,
|
||||
maxEdge,
|
||||
);
|
||||
}
|
||||
|
||||
/** Ersatzweg ohne Kamera: Bilddatei auswaehlen (z. B. am Rechner). */
|
||||
export async function imageDataFromFile(file, maxEdge = 1280) {
|
||||
const bitmap = await createImageBitmap(file);
|
||||
const data = drawScaled(bitmap, bitmap.width, bitmap.height, maxEdge);
|
||||
bitmap.close();
|
||||
return data;
|
||||
}
|
||||
Reference in New Issue
Block a user