Your First Triangle in WebGL 2

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

Drawing one triangle in WebGL takes about sixty lines, because the API does almost nothing for you: there is no default shader, no default camera and no notion of a shape. You supply two small programs that run on the GPU, a block of vertex data, and a description of how that data is laid out. Once those pieces are understood, every later WebGL page (textures, lighting, shadows, picking) is the same recipe with more data and longer shaders. This page builds the program one piece at a time, explains every call and the options it accepts, and finishes with the common reasons for a black canvas.

The facts were checked in November 2026. The versions documented are WebGL 2.0 and GLSL ES 3.00 (#version 300 es). The code is plain JavaScript in one HTML file and runs in any current evergreen browser (Chrome 56, Firefox 51, Edge 79 and Safari 15 and later, on desktop and mobile); WebGL 1 differences are called out where they matter, and the version and support story is in WebGL Versions and Browser Support. No library and no build step is needed: save the file and open it, or serve the folder with any static server.

This is step 1 of the raw WebGL track of the Bookshelf example. The track continues with a textured book-cover quad (Textures and Samplers), a lit rotating book (Lighting in Shaders) and an instanced shelf. The same first triangle in desktop OpenGL is Hello Triangle, and the shortest browser introduction is Canvas, WebGL & Three.js; this page goes deeper than both. The stages the triangle travels through are explained in The WebGL Rendering Pipeline.

The steps

Storyboard of five panels: a cleared canvas, one flat triangle, a triangle with per-vertex colours, an indexed quad and the textured book-cover quad
Figure 1. From a clear colour to the book-cover quad

The strip shows the Bookshelf track’s first steps. Panels 1 to 4 are built on this page; panel 5 comes next. In order, the program does:

  1. Get a context. Find the canvas, size its drawing buffer, call getContext with the webgl2 string.

  2. Compile the shaders. A vertex shader and a fragment shader, each checked for errors.

  3. Link them into a program, which is what you select before drawing.

  4. Upload the vertex data into a buffer object.

  5. Describe the layout in a vertex array object: which buffer, which attributes, which format.

  6. Every frame: match the canvas size to the screen, set the viewport, clear, select the program, bind the vertex array, draw.

Two columns: the calls that run once at start-up to create the program, buffer and vertex array object, and the calls that run every frame to resize, set the viewport, clear, select the program, bind the vertex array and draw
Figure 2. What runs once and what runs every frame

Steps 1 to 5 run once and create objects that live on the GPU side; step 6 runs in the animation loop. Keeping that split in the code from the start is the main habit that separates a fast WebGL program from a slow one: creating buffers or compiling shaders inside the frame loop is the most common beginner performance bug.

Step 1: the canvas and the context

A <canvas> element has two sizes. Its CSS size is how large it appears on the page. Its drawing buffer size is the width and height attributes, in device pixels, and defaults to 300 by 150 whatever the CSS says. WebGL renders into the drawing buffer and the browser scales it to the CSS size, so a canvas styled to fill a 1920-pixel-wide window but left at 300 pixels looks blurry. The fix is to set the buffer size from the element’s measured size multiplied by devicePixelRatio, shown in the full program below.

getContext("webgl2", attributes) returns a WebGL2RenderingContext, or null if WebGL 2 is unavailable. The attributes (alpha, antialias, depth, stencil, preserveDrawingBuffer, powerPreference, failIfMajorPerformanceCaveat and others) are fixed at creation and are listed in WebGL Versions and Browser Support. The defaults suit a first program. Two behaviours are worth knowing now:

  • The drawing buffer is presented to the page after the JavaScript task that drew into it ends and, by default, its contents are then cleared. There is no swapBuffers. Draw a complete frame inside one requestAnimationFrame callback; drawing half a frame in one task and the rest in another shows a flickering half-image unless preserveDrawingBuffer is true.

  • Changing canvas.width or canvas.height, even to the same value, reallocates and clears the drawing buffer. Do it only when the size actually changed.

The vertex data and how it reaches the shader

Flow from a Float32Array through a WebGLBuffer and a vertex array object with two attributes and a stride of 20 bytes to the vertex shader, plus the byte layout of one interleaved vertex
Figure 3. How the array travels to the vertex shader

Three objects cooperate, and the names confuse beginners:

  • The buffer (WebGLBuffer) is GPU-side memory. It stores bytes and has no idea what they mean.

  • The vertex array object (WebGLVertexArrayObject, VAO) is a small table of state: for each attribute number, which buffer it reads, the component type and count, the stride and the offset, and whether the attribute is enabled. In WebGL 2 a VAO is core; in WebGL 1 it needs the OES_vertex_array_object extension. A WebGL 2 context always has a default VAO bound, but you should create your own for each mesh.

  • The vertex shader inputs (in vec2 aPos, in vec3 aColor) receive, per vertex, the values the attributes yield.

Pure data (the buffer) is separated from its interpretation (the VAO), so one buffer can be read with different layouts, and all of a mesh’s attribute state is switched with a single bindVertexArray call. The detailed rules, including uniform blocks and std140 padding, are in Buffers, Attributes, Uniforms and VAOs. For this page the vertices are interleaved: each vertex stores its two position floats followed by its three colour floats, so one vertex is 20 bytes and the second attribute begins 8 bytes into it.

Steps 2 and 3: shaders and the program

A shader is a small program in GLSL ES. The vertex shader runs once per vertex and must write gl_Position, the vertex position in clip space. The fragment shader runs once per pixel-sized fragment covered by the triangle and writes a colour. The language is the subject of GLSL ES 1.00 and 3.00; this is what the first program needs.

#version 300 es
// vertex shader
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec3 aColor;
out vec3 vColor;
void main() {
    vColor = aColor;
    gl_Position = vec4(aPos, 0.0, 1.0);
}
#version 300 es
// fragment shader
precision highp float;
in vec3 vColor;
out vec4 outColor;
void main() {
    outColor = vec4(vColor, 1.0);
}

Things that cause errors in these twelve lines, in order of how often they bite:

  • #version 300 es must be the very first thing in the source: no blank line, no comment and no whitespace before it. A JavaScript template literal that starts on the next line after the backtick puts a newline first and the compile fails with a version error. Trim the string or start the text immediately after the backtick.

  • The fragment shader has no default float precision in GLSL ES, so it must declare one (precision highp float; or mediump). The vertex shader defaults to highp. (highp in fragment shaders is optional in WebGL 1 and mandatory in WebGL 2.)

  • The vertex out and the fragment in with the same name and type are matched by the linker. The rasteriser interpolates the three vertex colours across the triangle, which is why the corners are red, green and blue and the middle is a blend.

  • The fragment shader declares its own output. In GLSL ES 1.00 (WebGL 1) you write gl_FragColor and use attribute and varying instead of in and out.

  • layout(location = n) fixes the attribute number in the shader, so the JavaScript does not need getAttribLocation. Without it, the linker picks numbers and you must ask for them.

The compile and link functions can fail without throwing an exception. You must look at their status:

function compileShader(gl, type, source) {
  const shader = gl.createShader(type);          // gl.VERTEX_SHADER or gl.FRAGMENT_SHADER
  gl.shaderSource(shader, source);
  gl.compileShader(shader);
  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    const log = gl.getShaderInfoLog(shader);
    gl.deleteShader(shader);
    throw new Error("Shader compile failed:\n" + log);
  }
  return shader;
}

function linkProgram(gl, vs, fs) {
  const program = gl.createProgram();
  gl.attachShader(program, vs);
  gl.attachShader(program, fs);
  gl.linkProgram(program);
  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
    const log = gl.getProgramInfoLog(program);
    gl.deleteProgram(program);
    throw new Error("Program link failed:\n" + log);
  }
  // The linked program keeps what it needs; the shader objects can go.
  gl.detachShader(program, vs);
  gl.detachShader(program, fs);
  gl.deleteShader(vs);
  gl.deleteShader(fs);
  return program;
}

Reading the status immediately after compiling forces the browser to wait for the shader build, which stalls the page. For a single triangle that is harmless; for a real application with dozens of programs, compile everything first, link everything, and only then check the results, or use the KHR_parallel_shader_compile extension to poll without blocking. That technique is described in Performance and Debugging. MDN’s best-practices page recommends exactly this order.

Steps 4 and 5: the buffer and the vertex array object

const vertices = new Float32Array([
  //  x     y     r    g    b
   0.0,  0.6,  1.0, 0.2, 0.2,   // top, red
  -0.6, -0.6,  0.2, 1.0, 0.2,   // bottom left, green
   0.6, -0.6,  0.2, 0.2, 1.0,   // bottom right, blue
]);

const vao = gl.createVertexArray();
gl.bindVertexArray(vao);                      // everything below is recorded in this VAO

const vbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

const stride = 5 * Float32Array.BYTES_PER_ELEMENT;   // 20 bytes per vertex
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, stride, 0);                                  // aPos
gl.enableVertexAttribArray(1);
gl.vertexAttribPointer(1, 3, gl.FLOAT, false, stride, 2 * Float32Array.BYTES_PER_ELEMENT); // aColor

gl.bindVertexArray(null);

bufferData(target, data, usage) allocates the buffer and copies the typed array in. The usage argument is a hint to the driver about how often the contents change and who reads them:

Usage Meaning Typical use

STATIC_DRAW

written once, drawn many times

meshes that never change, such as the book

DYNAMIC_DRAW

written repeatedly, drawn many times

per-frame particle or instance data

STREAM_DRAW

written once, drawn a few times

data that changes every frame

STATIC_READ, DYNAMIC_READ, STREAM_READ (WebGL 2)

read back from the GPU

transform feedback results

STATIC_COPY, DYNAMIC_COPY, STREAM_COPY (WebGL 2)

GPU to GPU copies

transform feedback feeding another draw

vertexAttribPointer(index, size, type, normalized, stride, offset) takes six arguments:

Argument Meaning

index

The attribute number: 0 and 1 here, matching layout(location = n).

size

Components per vertex, 1 to 4. Two floats for aPos, three for aColor.

type

The data type in the buffer: FLOAT, BYTE, UNSIGNED_BYTE, SHORT, UNSIGNED_SHORT, and in WebGL 2 INT, UNSIGNED_INT, HALF_FLOAT and packed 2_10_10_10 formats.

normalized

For integer types, whether to map the range to 0 to 1 (unsigned) or -1 to 1 (signed). Colours stored as UNSIGNED_BYTE use true. Ignored for floats.

stride

Bytes from one vertex to the next. 0 means tightly packed with the same attribute only.

offset

Byte offset of this attribute inside the vertex, always a number of bytes, never elements.

For attributes that the shader reads as integers (ivec, uvec), WebGL 2 adds vertexAttribIPointer, which does not convert to float. The call reads from the buffer currently bound to ARRAY_BUFFER at the moment it is made; the association is then stored in the VAO. That is why the buffer is bound before the pointer calls and why unbinding it afterwards does not matter.

Step 6: clear, set the viewport, draw

The core of each frame is four calls:

  • gl.viewport(x, y, width, height) maps normalised device coordinates to pixels of the drawing buffer. Its default is the buffer size at context creation, and it is not updated when you resize the canvas: set it every frame or after every resize. A viewport that is too small draws a miniature scene in a corner; one that does not match the aspect ratio stretches it.

  • gl.clearColor(r, g, b, a) and gl.clear(gl.COLOR_BUFFER_BIT) fill the buffer. Add DEPTH_BUFFER_BIT and STENCIL_BUFFER_BIT when those buffers exist and are used. The clear colour is premultiplied alpha when premultipliedAlpha is true, so (0, 0, 0, 0) is a fully transparent canvas.

  • gl.useProgram(program) selects the shaders; gl.bindVertexArray(vao) selects the vertex layout.

  • gl.drawArrays(mode, first, count) draws count vertices starting at first.

The mode selects how vertices form primitives:

Mode Primitive from vertices v0, v1, v2, v3 …​

POINTS

one point per vertex, size from gl_PointSize

LINES

lines v0-v1, v2-v3, …​

LINE_STRIP

lines v0-v1, v1-v2, v2-v3, …​

LINE_LOOP

as a strip, plus a closing line to v0

TRIANGLES

triangles (v0, v1, v2), (v3, v4, v5), …​

TRIANGLE_STRIP

triangles (v0, v1, v2), (v2, v1, v3), …​ sharing two vertices each

TRIANGLE_FAN

triangles (v0, v1, v2), (v0, v2, v3), …​ around v0

Triangles are front-facing when their vertices appear counter-clockwise on the screen, the default of frontFace. Face culling is off by default in WebGL, so a clockwise triangle still draws; enable it with gl.enable(gl.CULL_FACE) once your meshes have consistent winding.

The numbers in the buffer are in normalised device coordinates (NDC): x and y range from -1 to 1 across the viewport, with y pointing up. The viewport transform turns those into window pixels, and the origin of window coordinates is the bottom-left corner, unlike the top-left origin of the 2D canvas and the DOM.

Left, the triangle in normalised device coordinates with vertices at 0 and 0.6, minus 0.6 and minus 0.6, and 0.6 and minus 0.6; right, the same triangle on a 400 by 300 pixel canvas with vertices at 200 and 240, 80 and 60, and 320 and 60
Figure 4. Mapping the triangle’s vertices from NDC to canvas pixels

The full chain, clip space, perspective divide, viewport transform and the tests that follow, is in The WebGL Rendering Pipeline; matrices that place and project a book arrive in Transforms and Cameras.

The complete program

Save this as index.html and open it. It resizes for high-DPI screens, checks every compile and link step, and reports WebGL errors during development.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>First triangle, WebGL 2</title>
  <style>
    html, body { margin: 0; height: 100%; background: #111827; }
    canvas { display: block; width: 100vw; height: 100vh; }
  </style>
</head>
<body>
  <canvas id="gl"></canvas>
  <script type="module">
    const canvas = document.getElementById("gl");
    const gl = canvas.getContext("webgl2");
    if (!gl) {
      document.body.textContent = "WebGL 2 is not available in this browser.";
      throw new Error("WebGL 2 unavailable");
    }

    // The first character of each shader source must be the # of the version line.
    const vertexSource = `#version 300 es
layout(location = 0) in vec2 aPos;
layout(location = 1) in vec3 aColor;
out vec3 vColor;
void main() {
  vColor = aColor;
  gl_Position = vec4(aPos, 0.0, 1.0);
}`;

    const fragmentSource = `#version 300 es
precision highp float;
in vec3 vColor;
out vec4 outColor;
void main() {
  outColor = vec4(vColor, 1.0);
}`;

    function compileShader(type, source) {
      const shader = gl.createShader(type);
      gl.shaderSource(shader, source);
      gl.compileShader(shader);
      if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        const log = gl.getShaderInfoLog(shader);
        gl.deleteShader(shader);
        throw new Error("Shader compile failed:\n" + log);
      }
      return shader;
    }

    function linkProgram(vs, fs) {
      const program = gl.createProgram();
      gl.attachShader(program, vs);
      gl.attachShader(program, fs);
      gl.linkProgram(program);
      if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        const log = gl.getProgramInfoLog(program);
        gl.deleteProgram(program);
        throw new Error("Program link failed:\n" + log);
      }
      gl.detachShader(program, vs);
      gl.detachShader(program, fs);
      gl.deleteShader(vs);
      gl.deleteShader(fs);
      return program;
    }

    // Development helper: drain the error queue and name the first error found.
    const errorNames = new Map([
      [gl.INVALID_ENUM, "INVALID_ENUM"], [gl.INVALID_VALUE, "INVALID_VALUE"],
      [gl.INVALID_OPERATION, "INVALID_OPERATION"], [gl.OUT_OF_MEMORY, "OUT_OF_MEMORY"],
      [gl.INVALID_FRAMEBUFFER_OPERATION, "INVALID_FRAMEBUFFER_OPERATION"],
      [gl.CONTEXT_LOST_WEBGL, "CONTEXT_LOST_WEBGL"],
    ]);
    function checkError(where) {
      let err;
      while ((err = gl.getError()) !== gl.NO_ERROR) {
        console.error(`WebGL error ${errorNames.get(err) ?? err} after ${where}`);
      }
    }

    const program = linkProgram(
      compileShader(gl.VERTEX_SHADER, vertexSource),
      compileShader(gl.FRAGMENT_SHADER, fragmentSource),
    );

    const vertices = new Float32Array([
       0.0,  0.6,  1.0, 0.2, 0.2,
      -0.6, -0.6,  0.2, 1.0, 0.2,
       0.6, -0.6,  0.2, 0.2, 1.0,
    ]);
    const FLOAT = Float32Array.BYTES_PER_ELEMENT;

    const vao = gl.createVertexArray();
    gl.bindVertexArray(vao);
    const vbo = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
    gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
    gl.enableVertexAttribArray(0);
    gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 5 * FLOAT, 0);
    gl.enableVertexAttribArray(1);
    gl.vertexAttribPointer(1, 3, gl.FLOAT, false, 5 * FLOAT, 2 * FLOAT);
    gl.bindVertexArray(null);
    checkError("setup");

    function resizeToDisplaySize() {
      const dpr = window.devicePixelRatio || 1;
      const width = Math.max(1, Math.round(canvas.clientWidth * dpr));
      const height = Math.max(1, Math.round(canvas.clientHeight * dpr));
      if (canvas.width !== width || canvas.height !== height) {
        canvas.width = width;     // reallocates and clears the drawing buffer
        canvas.height = height;
      }
    }

    function frame() {
      resizeToDisplaySize();
      gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
      gl.clearColor(0.07, 0.09, 0.15, 1.0);
      gl.clear(gl.COLOR_BUFFER_BIT);

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

      checkError("frame");   // remove or guard in production: getError can stall the pipeline
      requestAnimationFrame(frame);
    }
    requestAnimationFrame(frame);
  </script>
</body>
</html>

Points about this listing:

  • gl.drawingBufferWidth and gl.drawingBufferHeight are used for the viewport rather than the canvas attributes, because the browser may allocate a smaller buffer than requested if the size exceeds a device limit.

  • The loop redraws every frame although nothing moves. For a static scene, draw once and again only on resize; continuous rendering of an unchanging picture wastes power on phones and laptops.

  • checkError calls getError, a synchronous round trip to the GPU process. It is a development tool. MDN states that a well-formed page should generate only OUT_OF_MEMORY and CONTEXT_LOST_WEBGL errors, and that browsers stop printing detailed messages after a limit (32 in Firefox).

  • A canvas with CSS size zero (for example inside a hidden container) makes resizeToDisplaySize clamp to one pixel and nothing is drawn. ResizeObserver with device-pixel-content-box gives the exact device-pixel size and avoids moiré at fractional zoom levels; see Performance and Debugging.

Indexed drawing: the book-cover quad

A rectangle needs four corners but two triangles need six vertices. Indexed drawing stores each corner once and lists the triangles in an element array buffer. The quad below is panel 4 of the storyboard and becomes the textured book cover on the next step, so the vertices already carry texture coordinates (u, v) instead of colours.

// x, y, u, v : a portrait book cover, 0.8 wide and 1.2 tall in NDC
const quad = new Float32Array([
  -0.4, -0.6,  0.0, 0.0,
   0.4, -0.6,  1.0, 0.0,
   0.4,  0.6,  1.0, 1.0,
  -0.4,  0.6,  0.0, 1.0,
]);
const indices = new Uint16Array([0, 1, 2,   0, 2, 3]);   // two counter-clockwise triangles

const quadVao = gl.createVertexArray();
gl.bindVertexArray(quadVao);

const quadVbo = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, quadVbo);
gl.bufferData(gl.ARRAY_BUFFER, quad, gl.STATIC_DRAW);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 16, 0);    // position
gl.enableVertexAttribArray(1);
gl.vertexAttribPointer(1, 2, gl.FLOAT, false, 16, 8);    // uv

const ibo = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);              // the binding is stored in the VAO
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);

gl.bindVertexArray(null);

// in the frame:
gl.bindVertexArray(quadVao);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);   // count, index type, byte offset

The ELEMENT_ARRAY_BUFFER binding is part of the VAO state, so it must be bound while the VAO is bound, and unbinding the VAO afterwards is safe. The index type must match the array: UNSIGNED_BYTE, UNSIGNED_SHORT (up to 65,535 vertices) or, in WebGL 2 and in WebGL 1 with OES_element_index_uint, UNSIGNED_INT. The offset is in bytes, so for 16-bit indices it is twice the index number. Mismatching the type and the typed array is a frequent source of garbled meshes. Meshes and their layouts are covered in general terms in Meshes and Vertex Data.

When the canvas stays black

A black or empty canvas gives no message by itself. Work through this order; it finds almost every cause in a first triangle.

flowchart TD A["Canvas is black or empty"] --> B{"Console shows a WebGL or JavaScript error?"} B -- yes --> C["Fix the named call: check the shader info log and the link status"] B -- no --> D{"Is the canvas drawing buffer larger than 1 by 1 pixels?"} D -- no --> E["Give the canvas a CSS size and resize the drawing buffer"] D -- yes --> F{"Viewport set to the drawing buffer size?"} F -- no --> G["Call gl.viewport after every resize"] F -- yes --> H{"Program in use, VAO bound, count above 0?"} H -- no --> I["Call useProgram and bindVertexArray before the draw"] H -- yes --> J{"Vertex positions inside the range of minus 1 to 1?"} J -- no --> K["Add a projection or fix the data"] J -- yes --> L{"Output colour equal to the clear colour or alpha 0?"} L -- yes --> M["Change the clear colour or output alpha"] L -- no --> N["Check stride, offsets, attribute locations and typed array contents"]
Figure 5. Diagnosing a black canvas

The most frequent causes, in the order they occur:

Symptom Cause Remedy

Console: a shader compile error that mentions the version line

Whitespace or a newline before #version 300 es.

Start the source text right at the version line.

Console: a fragment shader compile error about missing precision

Fragment shader without a precision statement.

Add precision highp float; (or mediump).

Link fails, the info log mentions a varying

Vertex out and fragment in differ in name, type or interpolation.

Make them identical.

Nothing is drawn, no error

Triangle drawn with a different program or VAO bound, or the attribute is disabled.

Call enableVertexAttribArray while the VAO is bound and bind it before drawing.

Stretched or tiny image

Viewport left at its initial size after a resize.

Set viewport from drawingBufferWidth and drawingBufferHeight.

Triangle visible only from one side

Face culling is enabled and the winding is clockwise.

Disable culling, or reverse the vertex order.

Garbled triangle

Wrong stride, offset or type, or the typed array is not a Float32Array.

Print the byte layout and compare to the vertexAttribPointer calls.

INVALID_OPERATION or an out-of-range warning after drawArrays

count asks for more vertices than the bound buffer holds for an enabled attribute.

Reduce count or upload the missing data.

Flicker or a blank canvas, especially after resizing

canvas.width was assigned in the render loop on every frame, clearing the buffer.

Assign only when the size changed.

Tools for deeper inspection (Spector.js, browser developer tools, GPU capture) are discussed in Performance and Debugging; recovering from a lost context is in Context Loss and Robustness.

Porting notes: WebGL 1 and OpenGL

From To WebGL 2 Note

WebGL 1 shaders (attribute, varying, gl_FragColor)

#version 300 es, in, out, a declared output

Both can coexist in one page in separate programs; they cannot be mixed within one program.

WebGL 1 with OES_vertex_array_object

createVertexArray, bindVertexArray on the context

The extension object methods (createVertexArrayOES) are replaced by core methods.

C++ OpenGL glVertexAttribPointer with a pointer-cast offset

vertexAttribPointer with a plain number as the last argument

The offset is a number of bytes. Client-side arrays do not exist, a buffer is always required.

The OpenGL equivalent of this page is Hello Triangle, and the full mapping between the two APIs is in OpenGL and WebGL.

Where the books are outdated

Book What it teaches Today

WebGL: Up and Running (PAR), chapters 1 to 3

WebGL 1 only, "experimental-webgl" context, GLSL ES 1.00 with attribute and varying, gl_FragColor, no VAOs, a Sim.js wrapper around the loop

getContext("webgl2"), #version 300 es, VAOs in the core, requestAnimationFrame (or setAnimationLoop) directly, ES modules instead of a wrapper library. The concepts of buffer, shader and program are unchanged.

Three.js Cookbook (TCB), chapter 1 and Learning Three.js (LTJ), chapter 1

Feature detection with Detector.js, prefixed requestAnimationFrame, file:// loading

Check the result of getContext yourself, use the unprefixed API and a local server.

PAR chapter 3

Setting the viewport once at start-up

Set it again after each resize, using the drawing buffer size.

The old books also draw into a fixed-size canvas, so they ignore devicePixelRatio; on today’s phones and laptops with high-density screens this produces a visibly soft image unless the buffer is sized as shown above.

References