Fragment shader
377
We've done with the vertex shader. Now, let's do the same for the fragment one. Our simplest fragment shader may look like this:
#version 300 es
precision highp float;
out vec4 frag_color;
void main(void)
{
frag_color = vec4(1.0, 1.0, 1.0, 1.0);
}
Everything is almost the same, so we don't need to discuss it in details. The only thing I should note is this line:
out vec4 frag_color;
This is an output color of a pixel, RGB + alpha. You can actually pick any name here since it's the only output of a fragment shader.
OK, JavaScript-side:
<textarea id="fs">
#version 300 es
precision highp float;
out vec4 frag_color;
void main(void)
{
frag_color = vec4(1.0, 1.0, 1.0, 1.0);
}
</textarea>
<!-- ... -->
<script type="text/javascript">
const canvas = document.getElementById("canvas");
const gl = canvas.getContext("webgl2");
const fs = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fs, document.getElementById("fs").value);
gl.compileShader(fs);
if(!gl.getShaderParameter(fs, gl.COMPILE_STATUS))
{
alert(gl.getShaderInfoLog(fs));
}
else
{
alert("Fragment shader has been successfully compiled!");
}
</script>
As you can see, everything is almost the same as before. gl.FRAGMENT_SHADER
instead of gl.VERTEX_SHADER
, and that's all. And we're jumping into the next lesson.
Rate this post:
Lesson 6
Lesson 8
Share this page:
Learning plan
The very basics of how things are being presented and processed in 3D graphics
The very basics of steps you should perform to draw a triangle or a 3D model from scratch
Let's create a simple vertex shader, compile it, and check for compilation issues
7. Fragment shader
Now let's create a fragment shader, compile it and check for errors
8. GLSL program
It's time to link our shaders into a completed GLSL program
Now we need to create a GPU buffer and transfer a geometry data into it
10. First triangle
Everything is ready to draw our first triangle