How to Render Custom Sprites in Matter.js

Yes, you can render custom sprites using the default Matter.Render module in Matter.js. This article covers how to configure body definitions to display custom image textures, how to adjust sprite scaling and offsets, the required renderer settings, and the technical limitations of using the built-in canvas renderer instead of a dedicated graphics engine.

Enabling Sprites in the Default Renderer

The default renderer in Matter.js draws bodies as wireframes by default. To render custom images, you must first disable wireframes in your Render.create configuration:

const render = Matter.Render.create({
  element: document.body,
  engine: engine,
  options: {
    width: 800,
    height: 600,
    wireframes: false
  }
});

Setting wireframes: false instructs the canvas renderer to respect fill colors and sprite properties assigned to physics bodies.

Configuring the Body Sprite

To attach a custom sprite to a body, define the render.sprite object in the body's configuration options. The key property is texture, which accepts a URL or relative path to an image file (PNG, JPG, or SVG).

const spriteBody = Matter.Bodies.rectangle(400, 200, 64, 64, {
  render: {
    sprite: {
      texture: 'path/to/sprite.png',
      xScale: 1,
      yScale: 1
    }
  }
});

Matter.Composite.add(engine.world, spriteBody);

Available Sprite Properties

The render.sprite configuration supports four primary properties:

Matching Hitboxes to Sprite Dimensions

Matter.js does not automatically size a physics body to match the dimensions of an external image file. If your sprite image is 128x128 pixels, you must either:

  1. Create the body with corresponding dimensions (Bodies.rectangle(x, y, 128, 128)).
  2. Use xScale and yScale to match the visual image to a differently sized collision geometry.

If the collision body and the image size do not match, the physics boundary will not align with what is visually rendered on screen.

Limitations of Matter.Render

While Matter.Render supports static image textures, it is designed primarily as an inspection and prototyping tool. It has several limitations:

For production games requiring animated characters, high draw-call counts, or complex visual effects, use Matter.js purely for physics calculation and sync the body positions to a dedicated rendering engine such as PixiJS, Phaser, or Three.js.