How to Disable Mouse Interaction in Matter.js
In Matter.js, interactive physics simulations often rely on
Matter.MouseConstraint to allow users to drag, toss, and
manipulate bodies on the canvas. However, specific gameplay states, UI
menus, or cutscenes often require this user interactivity to be
temporarily paused. This guide explains the most effective techniques to
disable mouse interactions in a Matter.js scene and re-enable them
seamlessly without breaking your physics loop.
Method 1: Removing and Re-adding the MouseConstraint
The most common and robust way to disable mouse interaction is by
temporarily removing the MouseConstraint from the physics
world composite.
When initializing your scene, keep a reference to your
mouseConstraint:
const { Engine, Render, Runner, Bodies, Composite, Mouse, MouseConstraint } = Matter;
const engine = Engine.create();
const world = engine.world;
// 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 }
}
});
// Add to world initially
Composite.add(world, mouseConstraint);To temporarily disable mouse interaction, remove the constraint from the world:
function disableMouse() {
Composite.remove(world, mouseConstraint);
}To restore mouse interaction, add it back to the composite:
function enableMouse() {
Composite.add(world, mouseConstraint);
}Method 2: Modifying the Collision Filter Mask
If you prefer to keep the MouseConstraint inside the
world structure to avoid modifying the composite hierarchy, you can
adjust the constraint's collision filter.
Setting the collision mask to 0 prevents the mouse from
detecting collisions with any category of physics bodies:
// Store the original mask if using custom categories
const originalMask = mouseConstraint.collisionFilter.mask;
function disableMouse() {
// 0 means it will collide with nothing
mouseConstraint.collisionFilter.mask = 0x0000;
}
function enableMouse() {
// Restore collision detection
mouseConstraint.collisionFilter.mask = originalMask;
}This approach allows the mouse to still track position coordinates without physically grabbing or dragging any objects in the simulation.
Method 3: Disabling Pointer Events via CSS
If mouse interactions need to be blocked because of an HTML/DOM UI
overlay (such as a pause menu or modal), you can toggle the CSS
pointer-events property directly on the canvas element.
function disableMouse() {
render.canvas.style.pointerEvents = 'none';
}
function enableMouse() {
render.canvas.style.pointerEvents = 'auto';
}This approach stops all native mouse and touch input from reaching the Matter.js canvas listener, completely freezing any interaction until re-enabled.