How to Inspect Matter.js Render Frame Rate

Monitoring the frame rate of a Matter.js simulation is crucial for diagnosing physics lag, optimizing collision calculations, and ensuring smooth browser rendering. This guide provides direct, actionable methods to inspect your Matter.js frame rate using the built-in renderer options, programmatic event listeners, external performance monitors, and browser developer tools.

1. Use the Built-in showFPS Renderer Option

Matter.js includes a native debug overlay that displays the current frames per second directly on the canvas. To enable it, set the showFPS property to true within the options object when instantiating Matter.Render:

const render = Matter.Render.create({
    element: document.body,
    engine: engine,
    options: {
        width: 800,
        height: 600,
        wireframes: false,
        showFPS: true // Displays the real-time FPS counter on the canvas
    }
});

Matter.Render.run(render);

When enabled, a small text readout appears in the corner of the canvas indicating the current render FPS.

2. Calculate Frame Rate Programmatically

If you need to log the FPS, display it in a custom UI, or react to performance drops in your application logic, you can calculate the frame rate using the Matter.Runner event hooks.

let lastTime = performance.now();
let frameCount = 0;
let currentFps = 0;

Matter.Events.on(runner, 'afterTick', () => {
    const currentTime = performance.now();
    frameCount++;

    // Update FPS calculation every 1000ms
    if (currentTime - lastTime >= 1000) {
        currentFps = frameCount;
        frameCount = 0;
        lastTime = currentTime;
        console.log(`Current Matter.js FPS: ${currentFps}`);
    }
});

Alternatively, you can measure the delta between individual updates:

Matter.Events.on(runner, 'tick', (event) => {
    // runner.delta represents milliseconds elapsed per step (typically ~16.66ms for 60fps)
    const instantFps = Math.round(1000 / runner.delta);
});

3. Use an External Monitor (Stats.js)

For detailed visual profiling that includes frame rate graphs and memory usage alongside your canvas, integrate the standard stats.js utility:

const stats = new Stats();
stats.showPanel(0); // 0: fps, 1: ms, 2: mb
document.body.appendChild(stats.dom);

Matter.Events.on(render, 'beforeRender', () => {
    stats.begin();
});

Matter.Events.on(render, 'afterRender', () => {
    stats.end();
});

4. Inspect via Browser Developer Tools

To inspect the render frame rate without modifying your code:

  1. Open Developer Tools in Chrome or Edge (F12 or Ctrl+Shift+I / Cmd+Option+I).
  2. Press Ctrl+Shift+P (or Cmd+Shift+P on macOS) to open the Command Menu.
  3. Type Show Rendering and select the Rendering drawer.
  4. Check the Frame Rendering Stats box.

An overlay will appear in the top-right corner of the browser viewport displaying real-time FPS and GPU memory usage.