How to Change Background Color in Matter.js
This guide explains how to change the background color of a Matter.js canvas renderer. You will learn how to define a custom color during the initial setup, modify the color dynamically while the simulation is running, and set a transparent background to style the canvas directly with CSS.
Setting the Background During Initialization
When initializing the built-in renderer using
Matter.Render.create(), pass the background
property inside the options object. The value accepts any
valid CSS color string, such as a HEX code, RGB, HSL, or a color
name.
const render = Matter.Render.create({
element: document.body,
engine: engine,
options: {
width: 800,
height: 600,
wireframes: false, // Set to false to render full colors
background: '#1a1a2e' // Your custom background color
}
});
Matter.Render.run(render);Note: Ensure wireframes is set to false
if you also want your physics bodies to show custom fill colors rather
than the default wireframe outlines.
Changing the Background Dynamically
To update the background color after the renderer has already been
created, modify the render.options.background property
directly:
// Change the background color dynamically at runtime
render.options.background = '#e94560';The change will take effect on the next animation frame rendered by Matter.js.
Using a Transparent Background with CSS
If you want the background to be handled by a webpage background, a
CSS gradient, or an underlying HTML element, set the
background property to 'transparent':
const render = Matter.Render.create({
element: document.body,
engine: engine,
options: {
width: 800,
height: 600,
wireframes: false,
background: 'transparent'
}
});You can then control the background using standard CSS applied to the canvas element:
canvas {
background: linear-gradient(135deg, #1f4037, #99f2c8);
}