Socket
Socket
Sign inDemoInstall

canvas-record

Package Overview
Dependencies
18
Maintainers
1
Versions
18
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    canvas-record

Record a video in the browser or directly on the File System from a canvas (2D/WebGL/WebGPU) as MP4, WebM, MKV, GIF, PNG/JPG Sequence using WebCodecs and wasm when available.


Version published
Weekly downloads
370
decreased by-29.12%
Maintainers
1
Install size
8.29 MB
Created
Weekly downloads
 

Changelog

Source

4.0.0-alpha.4 (2023-02-24)

Features

  • move filename overwrite to start options (7f09aa5)

Readme

Source

canvas-record

npm version stability-experimental npm minzipped size dependencies types Conventional Commits styled with prettier linted with eslint license

Record a video in the browser or directly on the File System from a canvas (2D/WebGL/WebGPU) as MP4, WebM, MKV, GIF, PNG/JPG Sequence using WebCodecs and Wasm when available.

paypal coinbase twitter

Installation

npm install canvas-record

Usage

import { Recorder, RecorderStatus, Encoders } from "canvas-record";
import createCanvasContext from "canvas-context";

// Setup
const pixelRatio = devicePixelRatio;
const width = 512;
const height = 512;
const { context, canvas } = createCanvasContext("2d", {
  width: width * pixelRatio,
  height: height * pixelRatio,
  contextAttributes: { willReadFrequently: true },
});
Object.assign(canvas.style, { width: `${width}px`, height: `${height}px` });

const mainElement = document.querySelector("main");
mainElement.appendChild(canvas);

// Animation
let canvasRecorder;

function render() {
  const width = canvas.width;
  const height = canvas.height;

  const t = canvasRecorder.frame / canvasRecorder.frameTotal || Number.EPSILON;

  context.clearRect(0, 0, width, height);
  context.fillStyle = "red";
  context.fillRect(0, 0, t * width, height);
}

const tick = async () => {
  render();

  if (canvasRecorder.status !== RecorderStatus.Recording) return;
  await canvasRecorder.step();

  if (canvasRecorder.status !== RecorderStatus.Stopped) {
    requestAnimationFrame(() => tick());
  }
};

canvasRecorder = new Recorder(context, { name: "canvas-record-example" });

// Start and encode frame 0
await canvasRecorder.start();

// Animate to encode the rest
tick(canvasRecorder);

API

Encoder comparison:

EncoderExtensionRequired Web APIWASMSpeed
WebCodecsmp4 / webm / mkvWebCodecs✅ (embed, only for mp4)Fast
H264MP4mp4✅ (embed)Medium
FFmpegmp4 / webmSharedArrayBuffer✅ (need binary path)Slow
GIFgifWebWorkers (wip)Fast
Framepng / jpgFile System AccessFast
MediaCapturemkv / webmMediaStreamRealtime

Note:

  • WebCodecs 5-10x faster than H264MP4Encoder and 20x faster than FFmpeg (it needs to mux files after writing png to virtual FS)
  • FFmpeg (mp4 and webm) and WebCodecs (mp4) have a AVC maximum frame size of 9437184 pixels. That's fine until a bit more than 4K 16:9 @ 30fps. So if you need 4K Square or 8K exports, be patient with H264MP4Encoder (which probably also has the 4GB memory limit) or use Frame encoder and mux them manually with FFmpeg CLI.
  • WebCodecs is embedded from mp4-wasm for ease of use (FFmpeg will require encoderOptions.corePath)

Roadmap:

  • add debug logging
  • use WebWorkers for gifenc

Modules

index

Re-export Recorder, RecorderStatus, all Encoders and utils.

Classes

Recorder

Base Recorder class.

Functions

onStatusChangeCb(RecorderStatus)

A callback to notify on the status change. To compare with RecorderStatus enum values.

Typedefs

RecorderOptions : Object

Options for recording. All optional.

RecorderStartOptions : Object

Options for recording. All optional.

index

Re-export Recorder, RecorderStatus, all Encoders and utils.

Recorder

Base Recorder class.

Kind: global class Properties

NameTypeDefaultDescription
[enabled]booleantrueEnable/disable pointer interaction and drawing.

new Recorder(context, options)

ParamType
contextRenderingContext
optionsRecorderOptions

recorder.start(startOptions)

Start the recording by initializing and calling the initial step.

Kind: instance method of Recorder

ParamType
startOptionsRecorderStartOptions

recorder.step()

Encode a frame and increment the time and the playhead. Calls await canvasRecorder.stop() when duration is reached.

Kind: instance method of Recorder

recorder.stop()

Stop the recording and return the recorded buffer. If options.download is set, automatically start downloading the resulting file. Is called when duration is reached or manually.

Kind: instance method of Recorder

recorder.dispose()

Clean up

Kind: instance method of Recorder

RecorderStatus : enum

Enum for recorder status

Kind: global enum Read only: true Example

// Check recorder status before continuing
if (canvasRecorder.status !== RecorderStatus.Stopped) {
  rAFId = requestAnimationFrame(() => tick());
}

onStatusChangeCb(RecorderStatus)

A callback to notify on the status change. To compare with RecorderStatus enum values.

Kind: global function

ParamTypeDescription
RecorderStatusnumberthe status

RecorderOptions : Object

Options for recording. All optional.

Kind: global typedef Properties

NameTypeDefaultDescription
[name]string""""A name for the recorder, used as prefix for the default file name.
[duration]number10The recording duration in seconds. If set to Infinity, await canvasRecorder.stop() needs to be called manually.
[frameRate]number30The frame rate in frame per seconds. Use await canvasRecorder.step(); to go to the next frame.
[download]booleantrueAutomatically download the recording when duration is reached or when await canvasRecorder.stop() is manually called.
[extension]boolean"mp4"Default file extension: infers which Encoder is selected.
[target]string""in-browser""Default writing target: in-browser or file-system when available.
[encoder]ObjectA specific encoder. Default encoder based on options.extension: GIF > WebCodecs > H264MP4.
[encoderOptions]Object{}See src/encoders or individual packages for a list of options.
[onStatusChange]onStatusChangeCb

RecorderStartOptions : Object

Options for recording. All optional.

Kind: global typedef Properties

NameTypeDescription
[filename]stringOverwrite the file name completely.

License

All MIT:

MIT. See license file.

Keywords

FAQs

Last updated on 24 Feb 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc