Mastering WebGL: A Step‑by‑Step Hello World Triangle Tutorial

Learn the four main web drawing tools—HTML + CSS, SVG, Canvas 2D, and WebGL—understand when to choose each, and follow a detailed, code‑rich tutorial that walks through creating a WebGL context, shaders, buffers, and rendering a simple triangle.

Aotu Lab
Aotu Lab
Aotu Lab
Mastering WebGL: A Step‑by‑Step Hello World Triangle Tutorial

Four Common Web Drawing Tools

When building graphics on an H5 page, developers typically choose among four technologies: HTML + CSS, SVG, Canvas 2D, and WebGL. Each tool has distinct strengths and trade‑offs.

HTML + CSS is the simplest for static charts with few data points, allowing styling directly in markup. However, as the number of shapes grows, CSS becomes verbose and hard to maintain because it lacks logical semantics.

SVG provides scalable vector graphics and integrates tightly with HTML and CSS. It supports complex shapes such as arcs and Bézier curves, and its reuse syntax keeps code readable. The downside is that every graphic element becomes a DOM node, which can cause heavy layout and rendering costs for large data sets.

Canvas 2D offers a raster‑based drawing context with a rich API. While it requires more manual implementation of shapes and colors, once the basics are built it can replace the capabilities of HTML + CSS and SVG and is easier to extend.

WebGL is the Web implementation of OpenGL ES. It operates at a lower level, leveraging the GPU for massive parallelism, making it ideal for pixel‑level processing, large‑scale geometry, and 3D scenes.

Choosing the Right Tool

Start by assessing the complexity and quantity of the required graphics:

If the visual consists of only a few simple elements, use HTML + CSS for rapid development.

If the shapes are simple but numerous, or require curves, SVG is a good fit.

For complex structures with many elements, Canvas 2D provides the necessary flexibility.

When the number of primitives reaches a high magnitude, pixel‑level manipulation is needed, or 3D rendering is required, switch to WebGL.

WebGL Hello World

Unlike the other tools, a minimal WebGL program consists of roughly forty lines of code. Understanding these lines gives insight into the low‑level rendering pipeline.

Five Core Steps

Create a WebGL rendering context.

Compile and link shader programs (vertex and fragment shaders).

Create vertex data and upload it to a buffer.

Configure the GPU to read the buffer data.

Issue the draw call.

Creating the WebGL Context

const canvas = document.createElement('canvas');
const gl = canvas.getContext('webgl');

Compiling a Shader Program

const program = gl.createProgram();
// Attach compiled vertex and fragment shaders here
gl.linkProgram(program);
gl.useProgram(program);

Shaders are small programs that run on the GPU. The vertex shader processes each vertex's position, while the fragment shader determines the color of each pixel.

Vertex Shader Source

const vertex = `
  attribute vec2 position;
  void main() {
    gl_Position = vec4(position, 1.0, 1.0);
  }
`;
const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertex);
gl.compileShader(vertexShader);

The shader receives a 2‑component vector position and expands it to a 4‑component homogeneous coordinate for the GPU.

Uploading Vertex Data

const points = new Float32Array([
  -1, -1,
   0,  1,
   1, -1
]);
const bufferId = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, bufferId);
gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW);

A typed array stores three 2‑D vertices (six numbers). Using a typed array reduces memory usage and improves performance for large datasets.

Binding Data to the Shader

const vPosition = gl.getAttribLocation(program, "position");
gl.vertexAttribPointer(vPosition, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(vPosition);

This step tells the GPU how to interpret the buffer: each vertex consists of two floating‑point numbers representing X and Y coordinates.

Drawing the Triangle

gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, points.length / 2);

After clearing the color buffer, gl.drawArrays renders the vertices as triangles. Using gl.TRIANGLES groups every three vertices into a triangle; other primitives such as gl.POINTS would produce different results.

Conclusion

The same logic is encapsulated by higher‑level libraries like three.js, but understanding the raw WebGL steps helps troubleshoot issues and deepens knowledge of the underlying 3D graphics pipeline.

References

GPU and Rendering Pipeline: How to Draw the Simplest Geometry with WebGL? – https://time.geekbang.org/column/article/63c01cb24d76d96cfd6a9ce64db6a623/share?code=CsdMNTf%2FboqZugxI1qspWwJxCaw2PUoiTwhMmOZ4Klw%3D&source=app_share

ShaderHTML5
Aotu Lab
Written by

Aotu Lab

Aotu Lab, founded in October 2015, is a front-end engineering team serving multi-platform products. The articles in this public account are intended to share and discuss technology, reflecting only the personal views of Aotu Lab members and not the official stance of JD.com Technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.