How to change three.js background to transparent or other color with JavaScript?

In Three.js, you can change the background of your scene to be transparent or any solid color by adjusting the renderer object. Here’s how you can do it:

1. Set the Background to Transparent

If you want the background to be transparent, you can set the alpha property of the renderer to true, and then ensure that your scene’s background is transparent.

2. Set the Background to a Solid Color

If you want to set the background to a solid color, you can use the setClearColor method of the renderer and pass the desired color.

Here’s a code example demonstrating both scenarios:

// Create a scene
const scene = new THREE.Scene();

// Create a camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

// Create a renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);

// Set the background to transparent
renderer.setClearColor(0x000000, 0); // Second argument (alpha) set to 0 for transparency

// Append the renderer to the DOM
document.body.appendChild(renderer.domElement);

// Create a cube
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// Animate the cube
function animate() {
    requestAnimationFrame(animate);

    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;

    renderer.render(scene, camera);
}

animate();

In this example, we create a basic scene with a cube.

We set the background of the renderer to transparent by passing 0x000000 (black) as the clear color and 0 as the alpha value.

We append the renderer to the DOM.

Finally, we animate the cube.

If you want to set the background to a solid color, you can change the setClearColor line to something like renderer.setClearColor(0xffffff) and pass the desired color as an argument (in this case, white).