How to Create a MouseConstraint in Matter.js

Matter.js enables interactive 2D physics in the browser, and the MouseConstraint module allows users to click, drag, and interact directly with physics bodies inside a simulation. This guide provides a straightforward walkthrough on creating, configuring, and adding a MouseConstraint to your Matter.js engine and renderer.

1. Import Matter.js Modules

To implement mouse interactions, you need access to the Mouse and MouseConstraint modules alongside the core engine components:

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

2. Initialize the Engine and Renderer

Before attaching mouse controls, create your engine, renderer, and physics world:

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

Render.run(render);
Runner.run(Runner.create(), engine);

3. Create and Attach the MouseConstraint

Creating the interactive constraint involves three key steps: creating a Mouse instance linked to the canvas, initializing the MouseConstraint, and syncing the mouse with the renderer.

// 1. Create a mouse instance attached to the renderer's canvas
const mouse = Mouse.create(render.canvas);

// 2. Create the MouseConstraint
const mouseConstraint = MouseConstraint.create(engine, {
  mouse: mouse,
  constraint: {
    stiffness: 0.2, // Adjust how tightly bodies follow the pointer
    render: {
      visible: false // Set to true to show the drag line
    }
  }
});

// 3. Add the MouseConstraint to the physics world
Composite.add(engine.world, mouseConstraint);

// 4. Keep the mouse in sync with rendering (crucial for accurate coordinates)
render.mouse = mouse;

Useful Configuration Options

You can fine-tune how user interaction works using the options object in MouseConstraint.create():

Handling Events

The MouseConstraint emits custom events such as startdrag, enddrag, and mousemove, allowing you to trigger logic when a user interacts with a body:

Matter.Events.on(mouseConstraint, 'startdrag', (event) => {
  console.log('Started dragging body:', event.body);
});

Matter.Events.on(mouseConstraint, 'enddrag', (event) => {
  console.log('Released body:', event.body);
});