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:
- Top-Left
- Top-Right
- Bottom-Right
- 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
}
});- Higher Quality: Produces a smoother appearance by adding more vertices, but increases the computational overhead during collision detection.
- Lower Quality: Reduces the number of vertices, creating more pronounced flat bevels and optimizing performance.
Important Considerations
- Radius Constraints: The specified radius must not exceed half of the body's width or height. Exceeding valid dimensions will cause rendering errors or invalid collision hulls.
- Physics Behavior: Chamfering modifies the actual physical vertex hull of the body, meaning collisions and resting orientations will accurately reflect the rounded geometry rather than behaving as a simple visual filter.