GLSL built-in function

texture2D()

Reads the color of an image (texture) at a given 0..1 coordinate. Changing the coordinate before reading is how you distort, scroll or tile images.

Demo version: GLSL ES 1.00 / WebGL 1Demo stage: Fragment

Syntax

vec4 texture2D(sampler2D sampler, vec2 coord)
vec4 texture2D(sampler2D sampler, vec2 coord, float bias)

Parameters

sampler
The texture, declared as uniform sampler2D.
coord
Where to read: (0, 0) is the bottom-left corner, (1, 1) the top-right.
bias
Optional mipmap level bias. Rarely needed.

Return value

A vec4 color (red, green, blue, alpha), each 0.0 to 1.0.

Live example

Edit the code and the preview updates as you type.

How it works

A texture is an image the GPU can read from. texture2D(sampler, coord) returns the color at position coord, where (0.0, 0.0) is the bottom-left of the image and (1.0, 1.0) the top-right.

The power is in changing coord before reading:

coordinateeffect
uvthe image as it is
uv + offsetshifted
fract(uv * 2.0)repeated 2 x 2
uv + sin(...) * 0.01wavy distortion

The example does a wavy distortion in the top half and tiling in the bottom half.

The live example on this page provides a test image as u_texture. In the Playground, upload an image in the textures panel and rename its uniform to u_texture (it is called u_texture0 by default).

Typical uses

  • Post-processing: read the rendered scene and apply blur, color grading or distortion.
  • Image effects: ripples, pixelation (floor(uv * n) / n), chromatic aberration (read r, g and b at slightly different coordinates).
  • Lookup tables: store a gradient or noise in a texture and read it instead of computing it.

Common mistakes

  • Using texture instead of texture2D. In WebGL 1 (GLSL ES 1.00) the function is texture2D; texture only exists in WebGL 2.
  • Coordinates outside 0..1. What you get depends on the wrap mode: repeated, clamped to the edge, or mirrored.
  • Upside-down images. Image files start at the top-left, GL textures at the bottom-left; flip with 1.0 - uv.y if the image appears upside down.

Related functions