How to Create a Default Renderer in Matter.js

This article explains how to initialize and configure the default renderer in Matter.js to visualize 2D physics simulations in a web browser. By utilizing the built-in Matter.Render module, you will learn the essential setup process, including creating an engine, binding the renderer to an HTML element, defining canvas dimensions, and starting the rendering loop.

1. Import Matter.js Modules

To create a simulation and view it, you need to extract the core modules from the Matter.js library: Engine, Render, Runner, Bodies, and Composite.

const { Engine, Render, Runner, Bodies, Composite } = Matter;

2. Initialize the Engine

The engine manages the state and updates the physics simulation. Create it using Engine.create():

const engine = Engine.create();

3. Create the Renderer

Matter.js includes a canvas-based renderer via the Render.create() method. This method accepts a configuration object with three primary properties:

const render = Render.create({
  element: document.body,
  engine: engine,
  options: {
    width: 800,
    height: 600,
    wireframes: false, // Set to false to show solid colors instead of wireframes
    background: '#fafafa'
  }
});

Common Renderer Options

4. Add Bodies to the World

Before running the renderer, add bodies to the engine's composite world so there is content to draw:

// Create a falling box and a static ground
const box = Bodies.rectangle(400, 200, 80, 80);
const ground = Bodies.rectangle(400, 580, 810, 60, { isStatic: true });

// Add the bodies to the world
Composite.add(engine.world, [box, ground]);

5. Start the Engine and Renderer

To display the canvas and begin the physics loop, execute Render.run() and start a runner to step through the physics engine:

// Run the renderer
Render.run(render);

// Create and run the runner
const runner = Runner.create();
Runner.run(runner, engine);

Once executed, Matter.js injects a <canvas> element into the targeted DOM node and renders the physics simulation in real time.