Textures
Bring images, canvases, video and arrays of numbers into a shader.
A texture is an image on the GPU that shaders sample. createTexture makes one from anything WebGL can upload: an image or ImageBitmap that has loaded, a canvas, a video, or a typed array of pixels. Pass it to a renderer like any other uniform.
import { createContext, createRenderer, createTexture, updateTexture } from 'wtc-simplegl'
// Two textures in one shader: a checkerboard made from a typed array, and a
// canvas with a counter drawn on it, re-uploaded every second. Each sampler
// gets its own texture unit, so they're passed straight to setUniforms.
const vert = /* glsl */ `#version 300 es
in vec2 a_position;
out vec2 v_uv;
void main() {
v_uv = a_position * 0.5 + 0.5;
gl_Position = vec4(a_position, 0.0, 1.0);
}`
const frag = /* glsl */ `#version 300 es
precision highp float;
uniform sampler2D u_checker;
uniform sampler2D u_label;
uniform float u_aspect;
in vec2 v_uv;
out vec4 colour;
void main() {
vec2 p = v_uv * vec2(u_aspect, 1.0);
vec4 checker = texture(u_checker, p * 2.0) * 0.35;
// The label sits in the middle, at its own aspect ratio
vec2 q = (v_uv - 0.5) * vec2(u_aspect, 1.0) * vec2(0.5, 1.0) + 0.5;
vec4 label = all(greaterThan(q, vec2(0.0))) && all(lessThan(q, vec2(1.0))) ? texture(u_label, q) : vec4(0.0);
colour = label + checker * (1.0 - label.a);
}`
export default function (container) {
const ac = new AbortController()
const canvas = document.createElement('canvas')
container.appendChild(canvas)
const gl = createContext({
canvas,
signal: ac.signal,
attributes: { alpha: true, premultipliedAlpha: true, antialias: true }
})
// 2 × 2 texels, premultiplied blue and see-through, repeated
const checker = createTexture(gl, {
data: new Uint8Array([74, 158, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 74, 158, 255, 255]),
width: 2,
height: 2,
minFilter: gl.NEAREST,
magFilter: gl.NEAREST,
wrapS: gl.REPEAT,
wrapT: gl.REPEAT
})
// A 2D canvas to draw text on. flipY puts its top row at the top.
const label = document.createElement('canvas')
label.width = 512
label.height = 256
const ctx = label.getContext('2d')
const draw = (n) => {
ctx.clearRect(0, 0, 512, 256)
ctx.fillStyle = '#ff73b3'
ctx.font = '600 120px system-ui, sans-serif'
ctx.textAlign = 'center'
ctx.textBaseline = 'middle'
ctx.fillText(String(n), 256, 128)
}
draw(0)
const text = createTexture(gl, { img: label, flipY: true, generateMips: false })
const quad = createRenderer(gl, {
vert,
frag,
count: 3,
attributes: {
a_position: { data: new Float32Array([-1, -1, 3, -1, -1, 3]), size: 2 }
}
})
let shown = 0
return {
frame(time) {
const seconds = Math.floor(time)
if (seconds !== shown) {
shown = seconds
draw(seconds)
updateTexture(gl, text, label, { flipY: true })
}
quad.bindVAOs()
quad.setUniforms({
u_checker: checker,
u_label: text,
u_aspect: gl.canvas.width / gl.canvas.height
})
quad.render()
},
dispose() {
ac.abort()
quad.delete()
gl.deleteTexture(checker)
gl.deleteTexture(text)
gl.getExtension('WEBGL_lose_context')?.loseContext()
canvas.remove()
}
}
}From an image
createTexture needs an image that has already loaded. loadTexture loads one from a URL and makes the texture:
import { loadTexture } from 'wtc-simplegl'
const photo = await loadTexture(gl, '/images/photo.jpg', { flipY: true })Images from another origin need CORS headers. loadTexture asks for them (crossOrigin = "anonymous"), and rejects with the URL if the image can't load.
Which way up
Texture coordinates start at the bottom: y = 0 is the bottom row. Images and canvases start at the top. flipY: true flips them on upload, so the top of the image is at the top of the texture. Use it for images you'll show the right way up; leave it off for data, and for textures you'll only ever read in shader coordinates.
From data
Pass width, height and data, a typed array, instead of img. This is how to get lookup tables, positions and other numbers into a shader:
const positions = createTexture(gl, {
data: new Float32Array(1024 * rows * 2),
width: 1024,
height: rows,
format: gl.RG,
type: gl.FLOAT
})Leave out data for an empty texture. Float types (gl.FLOAT and gl.HALF_FLOAT) get the sized internal format they need, such as gl.RG32F here, and don't make mipmaps. Rows don't need to be a multiple of 4 bytes.
For exact values, read data textures with texelFetch in the shader, which takes whole texel coordinates and ignores filtering:
vec2 p = texelFetch(u_positions, ivec2(i % 1024, i / 1024), 0).xy;Options
| Option | Default | |
|---|---|---|
flipY | false | Flip on upload. |
wrapS, wrapT | gl.CLAMP_TO_EDGE | gl.REPEAT to tile, gl.MIRRORED_REPEAT to tile mirrored. |
minFilter | trilinear with mipmaps, else gl.LINEAR | gl.NEAREST for crisp pixels. |
magFilter | gl.LINEAR | gl.NEAREST for crisp pixels when scaled up. |
generateMips | true for 8-bit textures | Mipmaps keep a texture smooth when it's drawn small. |
format, type, internalFormat | gl.RGBA, gl.UNSIGNED_BYTE | For data, and float textures. |
32-bit float textures can't be filtered linearly on every device, so they default to gl.NEAREST where they can't.
Updating
updateTexture uploads new contents into an existing texture: the current frame of a video, a canvas you've drawn on, or new data. Mipmaps are made again if the texture uses them:
import { updateTexture } from 'wtc-simplegl'
// Each frame
updateTexture(gl, texture, video, { flipY: true })Pass the same flipY, format and type as when it was made. For data, pass width and height; they can differ from before.
In a shader
Every sampler uniform gets its own texture unit when the renderer is made. Pass the texture to setUniforms and it's bound to that unit whenever the renderer draws:
renderer.setUniforms({ u_image: photo, u_noise: noise })Because each renderer binds its own textures as it draws, renderers don't interfere with each other's units. A framebuffer target can be passed in place of a texture, as can an array of textures for a sampler array.
To bind textures yourself, set the sampler to a unit number instead, and bind it with gl.activeTexture and gl.bindTexture.
Freeing them
Textures are plain WebGLTextures, so free them with gl.deleteTexture(texture).
See also
- Framebuffers, to draw into a texture
- Lookups in a data texture and Video and live canvases
- API: createTexture, loadTexture, updateTexture, TextureOptions