learn GLSL from zero
ToolsCreate with shadersShader MakerFree online shader builderToolkitShader works ready for your siteSketcher LabPaint your landing’s hero with shaders3D StudioThe Three.js editor in your browser
GamesPlay with shadersOnomatoShaderType a word, blow it upThe WatcherAn eye that follows youAetherLiquid glass with an eye insideBloomcoreA word grows a garden of lightPyrokineThrow fire at the wallVoltaicThe pyramid throws lightningSurfSurf a shader ocean

Lesson 4 of 10 · GLSL for beginners

Coordinates

Every frag knows where it is.

Every frag on the screen has a position: two numbers, X and Y. X is horizontal (left-right), Y is vertical (bottom-top). Just like the coordinate plane.

Position X, position Y. The frag knows. Your decision.

Here is the key idea: every frag runs the code on its own, but it knows its own position. The frag at the bottom-left corner knows it is (0, 0). The one at the top-right knows it is the last one.

vec2If vec3 is a pack of 3 numbers, vec2 is a pack of 2. We use it for positions (X, Y). Here p is the frag position divided by the screen size, so it goes from 0 to 1 instead of 0 to 1920.

If you put p.x as red, the red increases to the right. Put p.y as green and the green increases upward. The color is the position.

TryChange p.x to p.y on the first line. What happens? Now put p.x in all three spots. And now?

The code

void main(){
  vec2 p = gl_FragCoord.xy / R;
  vec3 col = vec3(p.x, p.y, 0.3 + 0.2 * sin(T * 0.5));
  col = hueShift(col, 0.0);
  gl_FragColor = vec4(col, 1.);
}
close