Skip to content

Commit

Permalink
feat(dl-asset): add canvasVideoRecorder()
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Dec 10, 2021
1 parent 155358a commit 6736463
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
16 changes: 16 additions & 0 deletions packages/dl-asset/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,19 @@ export interface DownloadOpts {
*/
expire: number;
}

/**
* User options for {@link canvasRecorder}.
*/
export interface CanvasRecorderOpts
extends Pick<
MediaRecorderOptions,
"mimeType" | "bitsPerSecond" | "videoBitsPerSecond"
> {
/**
* Recording frame rate (fps)
*
* @defaultValue 60
*/
fps: number;
}
42 changes: 42 additions & 0 deletions packages/dl-asset/src/canvas.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { CanvasRecorderOpts } from "./api.js";
import { downloadWithMime } from "./raw.js";

/**
Expand Down Expand Up @@ -26,3 +27,44 @@ export const downloadCanvas = (
quality
);
};

/**
* Constructs, initializes and returns a `MediaRecorder` instance for the given
* canvas. The recording MUST be started & ended manually by the caller (via
* `.start()` and `.stop()`). The downloading starts only once sufficient frames
* were recorded, or latest when `.stop()` was called.
*
* @remarks
* The default recording format is WebM (VP9 codec) @ 60 fps, using the browser
* defined default bit rate.
*
* @param canvas
* @param fileName
* @param opts
*/
export const canvasRecorder = (
canvas: HTMLCanvasElement,
fileName: string,
opts?: Partial<CanvasRecorderOpts>
) => {
opts = { fps: 60, mimeType: "video/webm; codecs=vp9", ...opts };
const stream = canvas.captureStream(opts.fps);
const recorder = new MediaRecorder(stream, {
mimeType: opts.mimeType,
});
let blobs: Blob[] = [];
recorder.ondataavailable = (e) => {
if (e.data.size > 0) {
blobs.push(e.data);
downloadWithMime(
fileName,
new Blob(blobs, { type: opts!.mimeType }),
{
mime: opts!.mimeType!,
}
);
blobs = [];
}
};
return recorder;
};

0 comments on commit 6736463

Please sign in to comment.