Textures

Image, Video and Canvas Textures

A texture maps an image onto a surface: vertices carry texture coordinates (u, v, or s, t) from 0 to 1, and the fragment shader looks up colors with texture() (Texture Lookup Functions). The sixteenth part of webgl-helper.js wraps the calls that turn an image, canvas or video frame into a texture:

webgl-helper.js, sixteenth part: textures from images, canvases and videoJavaScript
// Section 3.12: a 2D texture from an image, canvas, video, ImageBitmap or ImageData, flipped
// so v = 1 is the source's top row; mipmapped, with anisotropy where supported, by default
GLH.texture = function (gl, source, options = {}) {
  const { mipmaps = true, wrap = gl.CLAMP_TO_EDGE, srgb = false, anisotropy = 8 } = options;
  const texture = gl.createTexture(), T = gl.TEXTURE_2D;
  gl.bindTexture(T, texture);
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(T, 0, srgb ? gl.SRGB8_ALPHA8 : gl.RGBA8, gl.RGBA, gl.UNSIGNED_BYTE, source);
  gl.texParameteri(T, gl.TEXTURE_WRAP_S, wrap);
  gl.texParameteri(T, gl.TEXTURE_WRAP_T, wrap);
  gl.texParameteri(T, gl.TEXTURE_MIN_FILTER, mipmaps ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  const ext = gl.getExtension('EXT_texture_filter_anisotropic');
  if (mipmaps) gl.generateMipmap(T);
  if (mipmaps && ext) gl.texParameterf(T, ext.TEXTURE_MAX_ANISOTROPY_EXT, anisotropy);
  return texture;
};
GLH.image = (url) => { const i = new Image(); i.src = url; return i.decode().then(() => i); };

The texture stays bound to the active unit. The cover art is six 256 x 384 PNGs from Canvas 2D's cover designer.

Subsections