Export Matter.js Canvas as a Base64 Image
Capturing a snapshot of your Matter.js physics simulation as a base64 string is a straightforward process achieved by accessing the underlying HTML5 canvas element and calling its native serialization method. This guide explains how to extract the canvas element from a Matter.js renderer and retrieve a real-time base64-encoded image string using native JavaScript.
1. Access the Renderer Canvas
Matter.js renders physical bodies onto a standard HTML5
<canvas> element using the Matter.Render
module. When you initialize your renderer via
Render.create(), the instance stores a reference to the
active canvas element in its canvas property.
// Access the canvas element directly from the render instance
const canvas = render.canvas;2. Convert the Canvas to a Base64 String
To capture an instant snapshot, call the native
toDataURL() method directly on the canvas element. By
default, this outputs a PNG-formatted base64 data URL:
// Capture as a standard PNG base64 string
const base64PNG = render.canvas.toDataURL('image/png');
// Alternatively, capture as a JPEG with custom quality (0.0 to 1.0)
const base64JPEG = render.canvas.toDataURL('image/jpeg', 0.85);3. Ensure Proper Timing
with afterRender
Because Matter.js clears and redraws the canvas on each frame of the
render loop, executing toDataURL() at an arbitrary time
might capture an incomplete draw call or a blank canvas. To ensure the
snapshot includes all rendered bodies, execute the capture hook directly
inside the Matter.js afterRender event:
Matter.Events.on(render, 'afterRender', function() {
const base64Image = render.canvas.toDataURL('image/png');
console.log(base64Image);
// Unbind if you only need a single instant snapshot
Matter.Events.off(render, 'afterRender');
});This ensures that all physics bodies, constraints, and custom viewports are fully drawn onto the context before the base64 conversion takes place.