Now that we have our virtual world (the Scene) and our viewpoint within it (the Camera), we need something to actually draw what the camera sees onto our screen. This is the job of the Renderer. In Three.js, the primary renderer is WebGLRenderer, which leverages the power of WebGL to paint pixels directly onto an HTML Canvas element. It's the engine that translates our 3D scene data into a 2D image that you can see.
To set up the renderer, we first create an instance of WebGLRenderer. This renderer needs to know where to draw. We achieve this by attaching its DOM element to our HTML page. Typically, you'll have a <div> or a <canvas> element in your HTML file. The renderer will then take over that element and render its output there.
const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );The setSize method is crucial. It dictates the resolution of the rendered output, essentially the width and height of our virtual canvas in pixels. It's a good practice to make this match the dimensions of the browser window so that your 3D experience fills the screen. We also have a convenient property renderer.domElement which is the actual <canvas> element that the renderer uses. We append this to our document's body so that it becomes visible.
The most critical function of the renderer is render(). This method takes our Scene and Camera objects and draws a single frame of what the camera sees onto the canvas. This operation happens typically within an animation loop, ensuring that the scene is constantly redrawn to reflect any changes, such as movement or rotation.
function animate() {
requestAnimationFrame( animate );
// Update your scene here (e.g., rotate objects)
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render( scene, camera );
}
animate();The requestAnimationFrame function is a browser API that's optimized for animations. It tells the browser that you want to perform an animation and requests that the browser call a specified function to update the animation before the next repaint. This creates a smooth, efficient animation loop. Inside this loop, we first update any elements in our scene (like rotating our cube, for example) and then call renderer.render(scene, camera) to draw the updated view.