• Introduction
  • 2D Plots
  • Edge Detection
  • Camera Systems
  • Color Interpolation
  • Terrain Systems
  • 3D Structure Editor
  • Edge Detection Basics

Introduction to WebGL

Getting Started

Ah, the red triangle - the "Hello, World!" of computer graphics! Just like how programmers traditionally start with printing "Hello, World!" to the console, graphics programmers have their own rite of passage: rendering a simple red triangle. It might seem basic, but this humble triangle introduces all the fundamental concepts we'll need for more complex graphics programming. It is a signal that the instrutions have been understood, and that further progress can be made. If it is the first time such a feat has been achieved, then do not downplay your accomplishment, this is a great start and milestone to your journey!

Key Steps

  • Setting up a WebGL context
  • Creating vertex data
  • Writing basic shaders
  • Drawing to the screen

Basic Triangle Demo

Here's a simple red triangle rendered using WebGL:

A basic red triangle

Understanding the Code


  // Vertex positions for a triangle
  const vertices = [
     0.0,  0.5,  0.0,  // top
    -0.5, -0.5,  0.0,  // bottom left
     0.5, -0.5,  0.0   // bottom right
  ];
  
  // Simple vertex shader
  attribute vec3 position;
  void main() {
    gl_Position = vec4(position, 1.0);
  }
  
  // Fragment shader for solid red color
  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  }

Setting Up WebGL Context

Before we can start rendering anything with WebGL, we need to set up our rendering context. This involves several key steps:

1. Creating the Canvas

First, we need an HTML canvas element. In React, we can create one using a ref to maintain a reference to the canvas element:

const canvasRef = useRef<HTMLCanvasElement>(null);

2. Obtaining the WebGL Context

Once we have our canvas, we can request a WebGL context. It's important to handle cases where WebGL might not be available:

const canvas = canvasRef.current;
if (!canvas) return;

const gl = canvas.getContext('webgl');
if (!gl) {
  console.error('WebGL not available');
  return;
}

3. Initial Setup

With our WebGL context, we need to configure some initial state. This typically includes:

  • Setting the viewport dimensions
  • Setting the clear color
  • Clearing the buffer
gl.viewport(0, 0, canvas.width, canvas.height);
gl.clearColor(0.0, 0.0, 0.0, 1.0);  // Black background
gl.clear(gl.COLOR_BUFFER_BIT);

4. Error Handling

WebGL operations can fail silently, so it's crucial to check for errors during setup:

function checkGLError(gl: WebGLRenderingContext, operation: string) {
  const error = gl.getError();
  if (error !== gl.NO_ERROR) {
    console.error(`WebGL error after ${operation}: ${error}`);
    return false;
  }
  return true;
}

5. Cleanup

When our component unmounts or we need to clean up resources, we should properly dispose of WebGL resources to prevent memory leaks:

useEffect(() => {
  // Setup code here...

  return () => {
    if (gl && program) {
      gl.deleteProgram(program);
    }
    // Delete other resources (buffers, textures, etc.)
  };
}, []);

Technical Note

This guide focuses on the practical implementation used in this project rather than covering theoretical cases or general best practices. The code examples show our specific approach to WebGL setup and rendering, optimized for our educational demos.

Color Interpolation

Now let's make it more interesting by adding different colors to each vertex:

Triangle with vertex color interpolation

Updated Shader Code


  // Vertex shader with color attribute
  attribute vec3 position;
  attribute vec3 color;
  varying vec3 vColor;
  
  void main() {
    vColor = color;
    gl_Position = vec4(position, 1.0);
  }
  
  // Fragment shader using interpolated color
  varying vec3 vColor;
  
  void main() {
    gl_FragColor = vec4(vColor, 1.0);
  }

Understanding the Triangle

Let's break down how a triangle is constructed in WebGL:

1. Three Vertices
2. Connected by Lines
3. Filled Triangle

Animated Triangle Fill

Watch as the triangle fills pixel by pixel:

Pixel-by-pixel triangle fill animation