How to Set Background Color in Three.js

This article provides a quick and straightforward guide on how to set the background color of a scene in Three.js. You will learn the three most common and effective methods to change the background color: using the scene’s background property, configuring the renderer’s clear color, and applying CSS to a transparent canvas.


Method 1: Using the Scene Background Property

The most common and direct way to set the background color is by assigning a THREE.Color object directly to the scene.background property.

import * as THREE from 'three';

const scene = new THREE.Scene();

// Set background color using a hexadecimal value
scene.background = new THREE.Color(0x1a1a1a); 

// Alternatively, you can use CSS color strings
scene.background = new THREE.Color('skyblue');
scene.background = new THREE.Color('rgb(255, 0, 0)');

This method is ideal because it binds the background color directly to the scene, meaning the color will automatically render whenever that specific scene is active.


Method 2: Using the Renderer’s Clear Color

Another approach is to set the clear color on the WebGL renderer. This defines the color that the renderer uses to clear the screen before drawing the next frame.

import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// Set the clear color (color, alpha/opacity)
renderer.setClearColor(0x222222, 1);

Note: If scene.background is set, it will override the renderer’s clear color.


Method 3: Using CSS with a Transparent Canvas

If you want to use a CSS gradient, an image, or match the background of your webpage, you can make the Three.js canvas transparent and style the HTML container using CSS.

First, initialize the renderer with the alpha parameter set to true:

const renderer = new THREE.WebGLRenderer({ alpha: true });

Next, ensure the renderer’s clear alpha is set to 0 (fully transparent):

renderer.setClearColor(0x000000, 0); // Second parameter is alpha

Finally, apply your desired background style to the HTML canvas element or its parent container in your CSS:

canvas {
  background: linear-gradient(to bottom, #114b5f, #1a936f);
}