Skip to content

WebGL API

This lesson explains WebGL API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 WebGL API Overview

The HTML5 WebGL API allows web applications to render hardware accelerated 2D and 3D graphics directly inside the browser using the <canvas> element. WebGL is based on OpenGL ES and gives JavaScript access to the GPU for fast visual rendering.

WebGL is commonly used for games, 3D product viewers, maps, data visualizations, scientific simulations, interactive backgrounds, design tools, and advanced browser-based graphics experiences.

Feature Description
API Name WebGL API
Main Element <canvas>
Main Context canvas.getContext("webgl")
Rendering Type GPU-accelerated 2D and 3D graphics
Core Concepts Shaders, buffers, attributes, uniforms, textures
Common Uses Games, viewers, simulations, charts, interactive graphics

Basic WebGL Context Example

<canvas
  id="glCanvas"
  width="500"
  height="300">
  Your browser does not support WebGL.
</canvas>
const canvas =
  document.getElementById("glCanvas");

const gl =
  canvas.getContext("webgl");

if (!gl) {
  console.log("WebGL is not supported.");
} else {
  gl.clearColor(0.1, 0.2, 0.4, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
}

This example gets a WebGL context from a canvas and clears it with a blue background color.

How WebGL API Works

Step Description Example Syntax
Create Canvas Provide a drawing area in the page. <canvas id="glCanvas"></canvas>
Get Context Access the WebGL rendering context. canvas.getContext("webgl")
Prepare Shaders Write programs for the GPU. gl.createShader(...)
Upload Data Send vertices or textures to GPU buffers. gl.bufferData(...)
Draw Scene Render shapes with WebGL commands. gl.drawArrays(...)

WebGL Core Components

Component Description Purpose
Canvas The surface where WebGL renders graphics. Display output to the user.
Context The WebGL rendering interface. Run drawing commands.
Vertex Shader Processes vertex positions and related data. Control geometry placement.
Fragment Shader Calculates final pixel colors. Color and shade rendered fragments.
Buffer Stores raw data such as vertices. Send geometry data to the GPU.
Program Linked shader combination. Tell WebGL how to render.

Set the Viewport and Clear the Canvas

const canvas =
  document.querySelector("#glCanvas");

const gl =
  canvas.getContext("webgl");

gl.viewport(
  0,
  0,
  canvas.width,
  canvas.height
);

gl.clearColor(0.95, 0.95, 0.98, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);

The viewport tells WebGL which portion of the canvas to render into. Clearing the color buffer resets the drawing surface for a new frame.

Create and Compile a Shader

function createShader(gl, type, source) {
  const shader =
    gl.createShader(type);

  gl.shaderSource(shader, source);
  gl.compileShader(shader);

  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    console.error(
      gl.getShaderInfoLog(shader)
    );

    gl.deleteShader(shader);
    return null;
  }

  return shader;
}

const vertexShaderSource =
  `
    attribute vec2 aPosition;

    void main() {
      gl_Position =
        vec4(aPosition, 0.0, 1.0);
    }
  `;

const fragmentShaderSource =
  `
    precision mediump float;

    void main() {
      gl_FragColor =
        vec4(0.2, 0.6, 0.9, 1.0);
    }
  `;

Shaders are small GPU programs. The vertex shader controls point positions, and the fragment shader controls pixel color.

Link Shaders into a Program

function createProgram(gl, vertexShader, fragmentShader) {
  const program =
    gl.createProgram();

  gl.attachShader(program, vertexShader);
  gl.attachShader(program, fragmentShader);
  gl.linkProgram(program);

  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    console.error(
      gl.getProgramInfoLog(program)
    );

    gl.deleteProgram(program);
    return null;
  }

  return program;
}

A program combines vertex and fragment shaders so WebGL can use them together during rendering.

Draw a Simple Triangle

const positions =
  new Float32Array(
    [
      0.0, 0.7,
      -0.7, -0.7,
      0.7, -0.7
    ]
  );

const positionBuffer =
  gl.createBuffer();

gl.bindBuffer(
  gl.ARRAY_BUFFER,
  positionBuffer
);

gl.bufferData(
  gl.ARRAY_BUFFER,
  positions,
  gl.STATIC_DRAW
);

const positionLocation =
  gl.getAttribLocation(
    program,
    "aPosition"
  );

gl.enableVertexAttribArray(positionLocation);

gl.vertexAttribPointer(
  positionLocation,
  2,
  gl.FLOAT,
  false,
  0,
  0
);

gl.useProgram(program);
gl.drawArrays(gl.TRIANGLES, 0, 3);

This example uploads three vertex positions to the GPU and draws them as a triangle using gl.TRIANGLES.

Animate a WebGL Scene

function render() {
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);

  gl.drawArrays(gl.TRIANGLES, 0, 3);

  requestAnimationFrame(render);
}

render();

WebGL animations usually clear the canvas and redraw the scene on each frame using requestAnimationFrame().

Feature Detection

function supportsWebGL() {
  const canvas =
    document.createElement("canvas");

  return !!canvas.getContext("webgl");
}

if (supportsWebGL()) {
  console.log("WebGL API supported.");
} else {
  console.log("WebGL API not supported.");
}

Feature detection is important because WebGL support can vary by browser, device capability, graphics driver, and security settings.

Common WebGL Methods

Method Description Common Use
getContext() Gets the WebGL rendering context. Initialize WebGL.
createShader() Creates a vertex or fragment shader. Define GPU logic.
shaderSource() Sets shader source code. Load GLSL source.
compileShader() Compiles a shader. Prepare shader for use.
createBuffer() Creates a GPU buffer. Store vertices or other data.
bufferData() Uploads data to a bound buffer. Send geometry to GPU.
drawArrays() Draws primitives from array data. Render points, lines, or triangles.

Common WebGL API Use Cases

  • 3D model viewers for products, architecture, or education.
  • Browser-based games and simulations.
  • Interactive charts and scientific data visualization.
  • Creative coding, particle systems, and animated backgrounds.
  • Maps, globes, and large rendering surfaces.
  • Image processing and custom visual effects.

WebGL API Best Practices

  • Always check whether a WebGL context is available before rendering.
  • Keep shaders small and focused when starting out.
  • Reuse buffers and programs instead of recreating them every frame.
  • Clean up textures, buffers, and programs when no longer needed.
  • Use requestAnimationFrame() for rendering loops.
  • Handle shader compilation and linking errors clearly during development.
  • Start with simple geometry before building full 3D scenes.

Performance Considerations

  • Minimize unnecessary state changes during rendering.
  • Batch draw calls where possible.
  • Upload static geometry once with gl.STATIC_DRAW when data does not change.
  • Reduce overdraw and expensive fragment shader work.
  • Pause animation when the page is hidden to save GPU and battery usage.
  • Test on lower-powered mobile devices, not just desktop hardware.

Common WebGL API Mistakes

  • Forgetting to check whether canvas.getContext("webgl") returned a valid context.
  • Ignoring shader compile or program link errors.
  • Mixing up attribute sizes, buffer formats, or vertex counts.
  • Redrawing without clearing the frame when the scene requires it.
  • Creating new buffers or shaders repeatedly inside animation loops.
  • Assuming WebGL behaves identically on every device and GPU.

WebGL API vs Canvas 2D

Feature WebGL API Canvas 2D
Rendering GPU accelerated graphics. CPU-oriented 2D drawing.
Best For 3D scenes, heavy visual effects, advanced rendering. Simple 2D graphics, charts, and drawings.
Complexity Higher learning curve. Easier to start with.
Shaders Required for most rendering pipelines. Not used.

Key Takeaways

  • The WebGL API brings GPU-accelerated graphics to the browser through the canvas element.
  • WebGL projects usually involve contexts, shaders, buffers, programs, and draw calls.
  • Start by clearing a canvas, compiling shaders, and drawing simple shapes such as triangles.
  • Feature detection, error handling, and performance awareness are important in production.
  • WebGL is powerful for advanced graphics but more complex than Canvas 2D.

Pro Tip

If you are new to WebGL, first make a triangle render reliably, then add colors, transformations, textures, and animation one concept at a time.