コンテンツにスキップ

HTMLVideoElementから画像を生成する

  • HTMLCanvasElement
  • HTMLVideoElement
  • Promise API
transfer-image.ts
interface OutputImage {
type: "png" | "jpeg" | "webp";
quality?: number;
}
interface TransferOptions {
canvas: HTMLCanvasElement;
video: HTMLVideoElement;
output: OutputImage;
}
interface TransfferedImage {
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);
});
}