A closer look at the Scene
We kind of glossed over the scene object in the last section, and I wanted to take a moment to really understand what it is and what options it presents us. As always, your best bet is to go directly to the Three.js docs section on the scene object, but I'll cover a few of them here and how to use them.
You can think of your scene as the backdrop or background that you'll be building in front of. It will set the tone for what you're building. Here's our cube from the previous section, with it's background set to 0xBBBBBB, a medium gray color.
But, what if we want to spice this up a bit? We can set the background to another color, or even a gradient. We can add fog to give it some depth and atmosphere.
// Scene with gradient background and fog
const scene = new THREE.Scene();
// Create gradient background using canvas
const gradientCanvas = document.createElement('canvas');
gradientCanvas.width = 2;
gradientCanvas.height = 512;
const ctx = gradientCanvas.getContext('2d');
const gradient = ctx.createLinearGradient(0, 0, 0, 512);
gradient.addColorStop(0, '#1a1a2e');
gradient.addColorStop(1, '#ff9900');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 2, 512);
const gradientTexture = new THREE.CanvasTexture(gradientCanvas);
scene.background = gradientTexture;
// Add fog (color, near, far)
scene.fog = new THREE.Fog(0xff9900, 0.5, 6);
// MeshStandardMaterial responds to fog (unlike MeshNormalMaterial)
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(1, 1, 1),
new THREE.MeshStandardMaterial({ color: 0x6699ff })
);
scene.add(mesh);
// MeshStandardMaterial needs lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(2, 2, 2);
scene.add(ambientLight);
scene.add(directionalLight);As you can see, with a little tweaking, you can add a lot of pizazz to your Three.js scene without much hassle.
Don't worry too much about the stuff that you don't yet understand here. We'll be covering things like Textures, Materials, and Lighting in later sections.
What's important, for now, is that you have some grounding in what a scene is, and what it is used for. It's your empty stage that you populate with actors.