Skip to main content

From position to color

Each pixel knows where it is. Turn that position into a color.

A fragment shader would be boring if every pixel got the same color. The power comes from the fact that each pixel knows where it is: the built-in gl_FragCoord gives you the pixel’s x and y position on screen. Divide it by u_resolution (the screen size, provided for you) and you get st — a coordinate from 0 to 1 across the screen, no matter its size.

  • st.x goes 0.0 at the left edge to 1.0 at the right edge
  • st.y goes 0.0 at the bottom to 1.0 at the top
  • Because you divided by u_resolution, it works at any screen size

If you feed st.x straight into the color, the left of the screen (x near 0) is black and the right (x near 1) is white — a gradient. Try it, then make one yourself.

Your turn

Make a gradient: black on the left, white on the right.

Compute st = gl_FragCoord.xy / u_resolution.xy, then use st.x as the color. vec3(st.x) makes a grey from it.

▶ Experiment with coordinates Try st.y, or 1.0 - st.x, or st.x * st.y, and watch what each does.
Wayline
Tools, assets and tutorials for game makers
Get started