How to Clear Canvas Background Color in WebGL

Clearing the canvas background color in WebGL is an essential first step in the rendering loop to ensure previous frames do not bleed into the current render. This process involves setting a target color state using the WebGL context and then executing a clear command on the drawing buffer. This guide explains the exact functions required—clearColor and clear—and provides a concise code example showing how to apply them.

To clear the background color of a WebGL canvas, you need to use two primary methods provided by the WebGL rendering context: gl.clearColor() and gl.clear().

1. Set the Clear Color

First, specify the color you want to use with gl.clearColor(red, green, blue, alpha). WebGL expects color values normalized as floating-point numbers between 0.0 and 1.0, rather than standard 0–255 RGB integers:

  • Red: 0.0 to 1.0
  • Green: 0.0 to 1.0
  • Blue: 0.0 to 1.0
  • Alpha: 0.0 (fully transparent) to 1.0 (fully opaque)

2. Clear the Buffer

Once the clear color is set, execute gl.clear() and pass the gl.COLOR_BUFFER_BIT mask. This tells WebGL to overwrite the color buffer with the color values defined in clearColor.

Complete Code Example

// Get the canvas element and its WebGL context
const canvas = document.getElementById("myCanvas");
const gl = canvas.getContext("webgl");

if (!gl) {
    console.error("WebGL not supported");
} else {
    // Set the clear color to dark blue (R: 0.1, G: 0.2, B: 0.4, Alpha: 1.0)
    gl.clearColor(0.1, 0.2, 0.4, 1.0);

    // Clear the color buffer with the specified color
    gl.clear(gl.COLOR_BUFFER_BIT);
}

Clearing Multiple Buffers

If you are working with 3D scenes that utilize depth testing or stencil buffers, you can clear multiple buffers simultaneously using the bitwise OR operator (|):

gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

Calling gl.clearColor() only sets the color state; the actual background will not update until gl.clear(gl.COLOR_BUFFER_BIT) is called. In animated scenes, place gl.clear() at the start of your render loop before drawing any geometry.