UV Coordinates Basics
In the last tutorial every pixel output the same color. To make the left side dark and the right side bright, the shader needs to know where each pixel is.
That's what UV coordinates are for.
From pixel position to UV
gl_FragCoord.xy gives the pixel's screen position — something like (142.0, 87.0). That number is tied to the canvas size and hard to work with.
Divide it by the canvas size to get a position in the 0.0 to 1.0 range:
After dividing:
- Left edge:
uv.x = 0.0 - Right edge:
uv.x = 1.0 - Bottom edge:
uv.y = 0.0 - Top edge:
uv.y = 1.0
Using uv.x to control color
uv.x goes from 0.0 on the left to 1.0 on the right — exactly right for brightness.
Set all three color channels to uv.x and you get a black-to-white gradient:
Left side uv.x = 0.0 → black. Right side uv.x = 1.0 → white.
Exercise
The exercise canvas starts black. Compute the UV coordinates and use uv.x to make it fade from black on the left to white on the right.
Answer Breakdown
Two steps: get UV, then use uv.x as brightness.
vec3(uv.x) is shorthand for vec3(uv.x, uv.x, uv.x) — equal channels means gray. As uv.x goes 0→1, the gray goes black→white.
u_resolution is a uniform holding the canvas size (e.g. 300×300). Dividing by it scales pixel coords into 0–1.
Try vec3(uv.y) — the gradient flips to bottom-to-top.