Hier ist eine Implementierung, die den aktuellen Frame von HTMLVideoElement als Bild extrahiert.
Erfassen Sie Videobilder mit der Canvas-API und erhalten Sie sie im Blob-Format.
Zu verwendende API
-HTMLCanvasElement
- HTMLVideoElement -Promise-API
Implementierung
interface OutputImage { type: "png" | "jpeg" | "webp"; quality?: number;}
interface TransferOptions { canvas: HTMLCanvasElement; video: HTMLVideoElement; output: OutputImage;}
interface TransferredImage { blob: Blob; width: number; height: number; type: string;}
function transferImage(options: TransferOptions): Promise<TransferredImage> { const { canvas, video, output } = options;
const height = video.videoHeight; const width = video.videoWidth;
return new Promise<TransferredImage>((resolve, reject) => { const ctx = canvas.getContext("2d"); if (!ctx) { reject(new Error("Context2D is not defined")); return; }
ctx.drawImage(video, 0, 0, width, height);
const type = `image/${output.type}`; const q = output.quality || 1;
function toBlob(blob: Blob | null) { if (blob) { resolve({ blob, width, height, type }); } else { reject(new Error("Failed to create blob from canvas")); } }
canvas.toBlob(toBlob, type, q); });}Punkte
- Ermitteln Sie die Videoauflösung mit
video.videoHeightundvideo.videoWidth - Zeichnen Sie den aktuellen Rahmen auf Canvas mit
ctx.drawImage(video, 0, 0, width, height) - Konvertieren Sie Canvas-Inhalte mit
canvas.toBlobin Blob - Verpacken Sie die asynchrone Verarbeitung mit Versprechen
Anwendungsbeispiel
const video = document.querySelector('video');const canvas = document.createElement('canvas');
const image = await transferImage({ canvas, video, output: { type: 'png', quality: 1 }});
// image.blob を使って画像をダウンロードしたり、表示したりできるconst url = URL.createObjectURL(image.blob);Zusammenfassung
Durch die Kombination von HTMLVideoElement und CanvasAPI können Sie jeden Frame eines Videos als Bild extrahieren.
Es kann zum Generieren von Miniaturansichten und zum Implementieren von Videovorschaufunktionen verwendet werden.
hsb.horse