When learning shader programming, the fragment shader is the most approachable and visually intuitive place to start. In this tutorial, we will use a minimal example to understand the basic structure of a GLSL shader and learn how to render a solid color across the entire canvas using gl_FragColor.
1. What Is a Fragment Shader?
The role of a fragment shader is simple in concept:
It determines the final color of every pixel on the screen.
You can think of it as a color calculator. The GPU executes the main() function once for every pixel, and the result defines that pixel’s color.
2. Complete Example Code
Let’s start by looking at the full shader code:
precision mediump float;
uniform float u_time;
uniform vec2 u_resolution;
void main() {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
This shader produces the following result:
👉 The entire canvas is filled with solid red.
3. Basic Structure of a GLSL Shader
3.1 Precision Declaration
precision mediump float;
This line defines the default precision for floating-point numbers:
-
lowp– low precision (fast, less accurate) -
mediump– medium precision (most common) -
highp– high precision (most accurate, slower)
In WebGL fragment shaders, declaring float precision is mandatory, otherwise the shader will fail to compile.
3.2 uniform Variables
uniform float u_time;
uniform vec2 u_resolution;
A uniform variable:
- Is passed in from the CPU (JavaScript)
- Has the same value for all pixels during a draw call
- Is read-only inside the shader
Common usage examples:
| Variable | Meaning |
|---|---|
u_time |
Elapsed time in seconds |
u_resolution |
Canvas resolution (width, height) |
In this example, these variables are not yet used, but declaring them early prepares us for animations and coordinate-based effects later.
4. main(): The Shader Entry Point
void main() {
...
}
-
main()is the only entry point of a GLSL shader - It is executed once per pixel
- You never call it manually
5. gl_FragColor: Outputting the Pixel Color
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
This is the most important line in the shader.
5.1 What Is gl_FragColor?
-
gl_FragColoris a built-in output variable - It defines the final color of the current fragment (pixel)
- Its type is
vec4
5.2 The RGBA Color Model
A vec4(r, g, b, a) represents:
| Channel | Description | Range |
|---|---|---|
| R | Red | 0.0 – 1.0 |
| G | Green | 0.0 – 1.0 |
| B | Blue | 0.0 – 1.0 |
| A | Alpha (opacity) | 0.0 – 1.0 |
vec4(1.0, 0.0, 0.0, 1.0)
This means:
- 100% red
- 0% green
- 0% blue
- Fully opaque
Result: pure red
5.3 Common Color Examples
// White
vec4(1.0, 1.0, 1.0, 1.0);
// Black
vec4(0.0, 0.0, 0.0, 1.0);
// Green
vec4(0.0, 1.0, 0.0, 1.0);
// Semi-transparent blue
vec4(0.0, 0.0, 1.0, 0.5);
6. Why Is the Entire Screen the Same Color?
Because:
- Every pixel executes
main() - Every pixel assigns the same value to
gl_FragColor - No coordinates, time, or varying data are used
As a result:
The whole canvas is filled with a single color.
Top comments (0)