How to Initialize a World in Matter.js

This guide provides a straightforward walkthrough for setting up a basic 2D physics simulation using Matter.js. You will learn the essential modules required to get started—specifically the Engine, Render, Runner, Bodies, and Composite modules—and how to combine them into a working browser-based demo featuring rigid bodies and collision detection.

Prerequisites

Include the Matter.js library in your project via an HTML <script> tag or install it using npm:

npm install matter-js

Essential Matter.js Modules

To build a world, you need five core modules:

Step-by-Step Implementation

  1. Create Module Aliases: Matter.js exposes all functionality under the global Matter object. Aliasing frequently used modules keeps code clean.
  2. Initialize the Engine: Instantiate the physics engine, which automatically creates an empty root world.
  3. Set Up the Renderer: Attach a canvas element to a container in your HTML document.
  4. Create Rigid Bodies: Define the shapes for the simulation, designating whether they are dynamic (affected by gravity/forces) or static (fixed in place).
  5. Add Bodies to the World: Register your bodies into engine.world using Composite.add.
  6. Run the Simulation: Start the runner and the renderer to initiate physics updates and canvas drawing.

Complete Example Code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Matter.js Basic World</title>
  <style>
    body {
      margin: 0;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-color: #f0f0f0;
    }
  </style>
  <!-- Load Matter.js from CDN -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
</head>
<body>
  <script>
    // 1. Alias Matter modules
    const { Engine, Render, Runner, Bodies, Composite } = Matter;

    // 2. Create the engine
    const engine = Engine.create();

    // 3. Create the renderer
    const render = Render.create({
      element: document.body,
      engine: engine,
      options: {
        width: 800,
        height: 600,
        wireframes: false
      }
    });

    // 4. Create bodies
    // Parameters: (x, y, width, height, [options])
    const box = Bodies.rectangle(400, 200, 80, 80, {
      render: { fillStyle: '#e74c3c' }
    });
    
    const ground = Bodies.rectangle(400, 580, 810, 60, { 
      isStatic: true,
      render: { fillStyle: '#2ecc71' }
    });

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

    // 6. Run the renderer and physics loop
    Render.run(render);
    const runner = Runner.create();
    Runner.run(runner, engine);
  </script>
</body>
</html>

Setting isStatic: true prevents the ground object from falling under the influence of gravity, allowing the dynamic box to fall, collide, and rest naturally on the surface.