The Magic Of The Fragment Shader

WebGLFundamentals | ShaderToy | The Art of Code
Last changed: 15.05.2021

The fragment shader is the second user definable shader that's run during the WebGL/OpenGL rendering pipeline. It is run for every pixel inside each GL primitive.
When you put a rectangle in 3D space exactly where the canvas is, you have complete control over each pixel inside the canvas via the fragment shader.
This is advantages since most devices have dedicated hardware for computer graphics, which will exectue the drawings in parallel to the CPU on the users end device.
Below is the simplest example of a 3D object drawn only using the fragment shader. 3D is simulated by making the color of each point whiter the smaller the height of
the parallelogram the vector from the camera to the point and the vector from the camera to the canvas span. Then the the point is rotated on a circular trajectory in
3D space.

Using a more complicated technique called ray marching more complex scenes can be described. Also light sources can be emulated. Ray marching works by stepping alongside a cast ray each step as far as the intersection of the last distantce circle and said ray. The radius of the circle is the minimum distance to an object in the scene relative to the last intersection. If the radius of the circle is smaller than a threshold an object is considered hit.