Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Scene, Camera and Renderer

WebGLRenderer in Depth

Configure the Three.js WebGLRenderer: antialiasing, alpha, pixel ratio, color space, tone mapping, clear color, render targets and context loss handling.

The WebGLRenderer is the part that talks to the graphics card. You create it once, hand it a scene and a camera each frame, and it produces the picture. This lesson covers the options and settings that change how that picture looks and performs: antialiasing, transparency of the canvas, sizing, color management, tone mapping, clearing, render targets and what to do when the GPU context is lost.

Constructor options

JavaScript
const renderer = new THREE.WebGLRenderer({
  canvas,                       // use an existing <canvas>
  antialias: true,              // smooth jagged edges (MSAA)
  alpha: false,                 // true = transparent canvas background
  powerPreference: "high-performance",
  preserveDrawingBuffer: false, // true only if you need toDataURL after the frame
  stencil: false,
  depth: true,
});

Most are fixed at creation: you cannot switch antialias later. A few notes:

  • antialias costs fill-rate but removes staircase edges. On high-density screens (pixel ratio 2+) it is often unnecessary.
  • alpha lets the page behind the canvas show through. Combine it with renderer.setClearColor(0x000000, 0) and no scene.background.
  • preserveDrawingBuffer keeps the last frame so canvas.toDataURL() works at any time. It is slower. A better way to take a screenshot is to call renderer.render(scene, camera) and toDataURL in the same task.

Size and pixel ratio

renderer.setSize(width, height) sets the canvas drawing buffer and its CSS size. Pass false as a third argument to leave CSS alone, which is the right choice when the canvas is sized by your layout:

JavaScript
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(container.clientWidth, container.clientHeight, false);

The pixel ratio multiplies the buffer size so that high-density displays get sharp lines. renderer.getDrawingBufferSize(vec2) tells you the real pixel size.

Color space and tone mapping

Two settings decide whether colors look right.

Color space. Colors you pick in a hex code like #4aa3ff are in the sRGB color space, while lighting math is done in linear space. Three.js handles the conversions automatically when you use renderer.outputColorSpace = THREE.SRGBColorSpace, which is the default today. For textures that contain color (photos, albedo), set texture.colorSpace = THREE.SRGBColorSpace; textures that contain data (normal, roughness, height maps) stay in the default linear space.

Tone mapping. Physically based lighting can produce values far brighter than white. Tone mapping compresses that range so highlights do not clip to flat white.

Constant Character
THREE.NoToneMapping None; clips bright values (default)
THREE.ACESFilmicToneMapping Cinematic contrast, slightly desaturated brights
THREE.ReinhardToneMapping Soft, simple roll-off
THREE.CineonToneMapping Filmic, strong shoulder
THREE.AgXToneMapping Neutral, preserves hues in highlights
THREE.NeutralToneMapping Designed to keep product colors accurate
JavaScript
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.0; // brightness before mapping
Tone mapping comparison

With a bright light, None clips the highlights into flat white blobs; the other settings keep gradient detail. Pick one and set it once at startup; changing it later requires material.needsUpdate = true, as the demo does.

Clearing and the clear color

Before each frame the renderer clears the canvas to a color. Use scene.background for a color or texture tied to a scene, or the renderer's clear color when you want a transparent or constant background:

JavaScript
renderer.setClearColor(0x101820, 1); // color, alpha
renderer.autoClear = false;          // you manage clearing manually
renderer.clear();                    // clear color, depth and stencil
renderer.clearDepth();               // clear only the depth buffer

Turning autoClear off is how you draw an overlay scene on top of the main one: render the first scene, call clearDepth(), then render the second.

Render targets

Instead of the screen, the renderer can draw into a WebGLRenderTarget, an off-screen texture. This is the basis for mirrors, security cameras, picture-in-picture, post-processing and the CubeCamera you met earlier.

JavaScript
const target = new THREE.WebGLRenderTarget(512, 512);
renderer.setRenderTarget(target);
renderer.render(scene, otherCamera);
renderer.setRenderTarget(null);       // back to the canvas
material.map = target.texture;        // use the result as a texture
A TV screen: render target as a texture

Context loss

Browsers can discard the GPU context, for example when the GPU driver resets or too many contexts exist. The canvas fires webglcontextlost and later webglcontextrestored. Three.js restores its internal state automatically, but you should prevent the default so the browser attempts a restore, and pause your loop:

JavaScript
renderer.domElement.addEventListener("webglcontextlost", (e) => {
  e.preventDefault();
  renderer.setAnimationLoop(null);
});
renderer.domElement.addEventListener("webglcontextrestored", () => {
  renderer.setAnimationLoop(tick);
});

Browsers limit live contexts per page (often 16). If you build many small viewers on one page, share one renderer or dispose the ones you no longer need with renderer.dispose().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which constructor option lets the page show through the canvas?

    alpha: true creates a canvas with an alpha channel. Also avoid setting scene.background.
  2. 2. What is tone mapping for?

    Lighting can produce values above 1.0. Tone mapping rolls them off smoothly.
  3. 3. How do you draw the scene into an off-screen texture?

    A WebGLRenderTarget acts as an alternative framebuffer; its .texture can be used in materials.
  4. 4. Why call event.preventDefault() in a webglcontextlost handler?

    Without it the browser assumes you do not want the context back.

Summary

  • Choose antialias, alpha and powerPreference when creating the renderer; they cannot change later.
  • Use setPixelRatio(Math.min(dpr, 2)) and setSize on resize.
  • Set outputColorSpace (default sRGB), tag color textures as sRGB and pick a tone mapping for bright lighting.
  • Render targets draw into textures, enabling mirrors, screens and post-processing.
  • Handle webglcontextlost and dispose renderers you no longer need.

Next: Vectors, Matrices and Quaternions