Attach Matter.js Renderer to an HTML Element
By default, Matter.js creates a new <canvas>
element and appends it directly to the HTML <body>.
This article demonstrates how to override that default behavior and
attach the Matter.js renderer to a specific container element (such as a
<div>) or bind it directly to an existing
<canvas> element in your DOM using the
Render.create configuration options.
Method 1: Appending to a Container Element
If you want Matter.js to generate the <canvas>
automatically inside a specific container, pass that container's DOM
node to the element property inside
Render.create.
HTML
<div id="physics-container" style="width: 800px; height: 600px;"></div>JavaScript
const { Engine, Render, Runner, Bodies, Composite } = Matter;
// 1. Create the physics engine
const engine = Engine.create();
// 2. Select the target HTML container
const container = document.getElementById('physics-container');
// 3. Create the renderer and assign the container to 'element'
const render = Render.create({
element: container,
engine: engine,
options: {
width: 800,
height: 600,
wireframes: false
}
});
// 4. Run the renderer and physics engine
Render.run(render);
const runner = Runner.create();
Runner.run(runner, engine);Method 2: Binding to an Existing Canvas
If you already have a <canvas> element defined in
your HTML and want Matter.js to render directly onto it, use the
canvas property instead of element.
HTML
<canvas id="physics-canvas" width="800" height="600"></canvas>JavaScript
const { Engine, Render, Runner } = Matter;
const engine = Engine.create();
// Select the existing canvas element
const canvasElement = document.getElementById('physics-canvas');
// Pass the canvas directly to the renderer
const render = Render.create({
canvas: canvasElement,
engine: engine,
options: {
width: 800,
height: 600,
wireframes: false
}
});
Render.run(render);
const runner = Runner.create();
Runner.run(runner, engine);Key Differences
element: Expects an HTML container element (like a<div>). Matter.js creates a<canvas>node and inserts it inside this element as a child.canvas: Expects an existing HTML<canvas>element. Matter.js draws directly to this canvas without creating any new elements. If bothelementandcanvasare supplied, thecanvasoption takes precedence.