Canvas Encoder
The CanvasEncoder
is a powerful tool for creating video recordings directly from a canvas element in the browser, ideal for capturing canvas-based games or animations without the need for our Composition
object.
Basic Usage
Start by creating a canvas element and setting its dimensions to match your desired video resolution:
Configuration Options
The CanvasEncoder
constructor accepts an optional second argument to configure the output settings. The default configurations are:
Video Encoding
After setting up the encoder, you can encode individual frames from the canvas to create your video. The following example creates a 3-second video by encoding 90 frames:
Audio Encoding (Optional)
To add audio to your video, you can use the Web Audio API. The CanvasEncoder
supports encoding audio buffers along with the video:
The audio will be automatically resampled to match the output configuration, so you don't need to worry about sample rate differences.
Note: By adding the audio, the resulting video duration will be 6 seconds, as that's the duration of the sound effect. In production you want to keep the video and audio durations synced.
Exporting the Video
Once you've encoded all the video frames and audio data, finalize the encoding process and export the result as an MP4 file:
The blob
method returns a Blob
containing the video with a video/mp4
MIME type. You can then save or process this blob as needed.