How to Detect Drag Release in Matter.js

This article explains how to detect when a user releases a dragged physics body in a Matter.js simulation. By using the MouseConstraint module along with the Events module, you can easily attach an event listener to capture the exact moment a body is dropped and access the specific body that was released.

Setting Up the MouseConstraint

Matter.js handles user interaction through the Matter.MouseConstraint module. When you add a mouse constraint to your engine's world, it tracks mouse interactions and allows physics bodies to be clicked and dragged.

To set up the mouse and mouse constraint:

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

// Create engine and renderer
const engine = Engine.create();
const render = Render.create({
  element: document.body,
  engine: engine
});

// Create mouse and mouse constraint
const mouse = Mouse.create(render.canvas);
const mouseConstraint = MouseConstraint.create(engine, {
  mouse: mouse,
  constraint: {
    stiffness: 0.2,
    render: {
      visible: false
    }
  }
});

Composite.add(engine.world, mouseConstraint);
render.mouse = mouse;

Listening for the enddrag Event

The MouseConstraint object provides custom events related to dragging. To detect when a user releases a body, use Events.on() to listen for the enddrag event on the mouseConstraint instance.

Events.on(mouseConstraint, 'enddrag', function(event) {
  const releasedBody = event.body;
  
  console.log('Body released:', releasedBody);
  
  // Custom logic (e.g., check body position, trigger sound, change body properties)
  if (releasedBody) {
    releasedBody.render.fillStyle = '#ff0000';
  }
});

Key Event Properties

When the enddrag event fires, the callback receives an event object containing:

Difference Between mouseup and enddrag

While mouseConstraint also supports a standard mouseup event, mouseup fires every time the mouse button is released, regardless of whether a body was selected. In contrast, enddrag only fires if an actual physics body was being dragged and then released, making it the most efficient way to detect a dropped object.