Create a Capsule Shape Using Chamfer in Matter.js

Matter.js does not feature a dedicated capsule primitive, but you can create an accurate capsule collider by applying a chamfer to a standard rectangle body. This article explains how to configure a rectangle's dimensions and chamfer radius to produce a capsule, provides a ready-to-use code implementation, and covers key settings such as vertex quality.

How the Chamfer Method Works

A capsule (also known as a stadium shape) consists of a rectangle capped by two semicircular ends. In Matter.js, the chamfer property bevels the corners of a polygon by generating additional vertices along a curve.

To form a true capsule:

  1. Choose the capsule orientation (vertical or horizontal).
  2. Set the chamfer radius to exactly half of the shorter dimension.
  3. For a vertical capsule of width \(W\) and height \(H\) (where \(H > W\)), the chamfer radius must be \(W / 2\).
  4. For a horizontal capsule where \(W > H\), the chamfer radius must be \(H / 2\).

Applying this radius rounds the adjacent corners together, forming seamless semicircular caps on both ends of the body.

Code Example

To generate a vertical capsule, define the rectangle and pass the chamfer configuration in the body options:

const Matter = require('matter-js');
const { Bodies } = Matter;

const x = 400;
const y = 300;
const width = 60;
const height = 140;

// Radius must equal half the width for a vertical capsule
const capsuleRadius = width / 2;

const capsule = Bodies.rectangle(x, y, width, height, {
  chamfer: {
    radius: capsuleRadius,
    quality: 8 // Controls the smoothness of the curve
  },
  render: {
    fillStyle: '#2ecc71'
  }
});

Configuring Chamfer Settings

The chamfer option accepts two primary properties:

Chamfer vs. Compound Bodies

Using a chamfered rectangle is generally preferred over building a compound body made of two circles and a rectangle: