Understanding the Matter.js Body Area Property
This article provides a comprehensive overview of the
area property in Matter.js physics bodies. You will learn
what the property represents, how the 2D physics engine calculates it,
its relationship with mass and density, and how to work with it
effectively when manipulating geometric bodies.
What is the area
Property?
In Matter.js, the area property represents the total
two-dimensional surface area of a rigid body, measured in square pixels.
It is a numerical value assigned to every Matter.Body
instance, calculated based on the polygon defined by the body's
vertices.
For simple primitive bodies—such as rectangles or regular polygons—the area corresponds directly to standard geometric formulas (for example, width multiplied by height for a rectangle). For circles, Matter.js approximates the area using a polygon representation with multiple vertices.
How Matter.js Calculates Area
Matter.js computes the area using the Shoelace formula (or Gauss's
area formula) applied to the ordered list of vertices that form the
body. If a body is a composite structure composed of multiple sub-bodies
(parts), the primary body's area is the sum of the
individual areas of all its constituent parts.
// Example: Accessing the area of a body
const box = Matter.Bodies.rectangle(400, 200, 80, 50);
console.log(box.area); // Outputs: 4000Because the area is bound to the geometry, it updates automatically
whenever a body's geometry changes, such as when assigning new vertices
via Matter.Body.setVertices(body, vertices).
The Relationship Between Area, Density, and Mass
The primary role of the area property in Matter.js is to
establish realistic physical behavior by determining mass. By default,
Matter.js assigns a standard density (typically 0.001) to
new bodies. Mass is computed dynamically using the following
formula:
\[\text{mass} = \text{density} \times \text{area}\]
When you scale a body using
Matter.Body.scale(body, scaleX, scaleY), its vertices
expand or contract, causing the area to change
proportionally. Consequently, the mass updates to reflect the new size
unless the body is configured as static.
Key Considerations
- Read-Only Behavior: You should not manually
overwrite
body.area. Instead, modify the body's dimensions using scaling functions or by supplying new vertex sets so the engine can recalculate the correct area, mass, and inertia automatically. - Compound Bodies: When creating compound bodies
using
Matter.Body.create({ parts: [...] }), the engine aggregates the areas of all non-parent parts to determine the composite object's total mass and center of mass.