How to Create Chamfered Rectangles in Matter.js

This guide explains how to define chamfered or rounded edges on a rectangle using the Matter.js 2D physics engine. By utilizing the built-in chamfer property available in the body options, you can soften sharp rectangular corners with a uniform radius or specify unique radii for individual corners to suit your simulation's needs.

Using the Chamfer Property

To create a chamfered rectangle, pass a chamfer object inside the options argument of the Matter.Bodies.rectangle factory method.

The basic syntax requires specifying a radius value, which defines the distance from each corner where the rounding or beveling begins:

const { Bodies } = Matter;

// Create a rectangle with uniform chamfered corners
const chamferedBox = Bodies.rectangle(400, 200, 100, 100, {
    chamfer: {
        radius: 15
    }
});

Configuring Individual Corners

Matter.js allows you to control each corner independently by passing an array of numbers to the radius property instead of a single integer. The values map sequentially starting from the top-left corner and proceeding clockwise:

  1. Top-Left
  2. Top-Right
  3. Bottom-Right
  4. Bottom-Left
const asymmetricalBox = Bodies.rectangle(400, 200, 120, 80, {
    chamfer: {
        radius: [20, 10, 0, 5]
    }
});

A value of 0 leaves that specific corner completely square.

Adjusting Chamfer Quality

By default, Matter.js approximates rounded corners by generating intermediate vertices. You can control the smoothness of the curve using the quality property within the chamfer configuration:

const smoothBox = Bodies.rectangle(400, 200, 150, 100, {
    chamfer: {
        radius: 25,
        quality: 8 // Higher values create smoother curves
    }
});

Important Considerations