WebGL Textures & Vertices

Beginner's Guide

Page Forty Eight

The Fragment Shader

This section covers the default fragment shader line by line. The file GLControl.js defines a default vertex and default fragment shader. If a Web page includes a shader, then the controller uses the shader. Otherwise the controller uses shaders defined in GLControl.js. The book's examples all use the default shaders.

Fragment Shader Introduction

The default fragment shader samples a texture. The fragment shader retrieves color from a texture at a specific location. The built in variable gl_FragColor receives the color. gl_FragColor describes the output color for the particular fragment. The fragment displays on the rendering surface. The Web page's canvas element serves as a rendering surface for the book's examples. gl_FragColor of type vec4, represents red, green, blue, and alpha channels for one color.

The fragment shader section presents a few new concepts for readers unfamiliar with shaders. However later sections in the book demonstrate how features work together. The section titled Prepare Textures begins the discussion. Subsections explain how to upload a texture to the GPU, then assign the texture to a sampler2D.

The following listing includes the entire fragment shader. Line numbers help identify each line for discussion.

1. precision mediump float;
2. uniform sampler2D u_sampler0;
3. varying vec2 v_tex_coord0;
4. void main(void) {
5. gl_FragColor = texture2D(u_sampler0, v_tex_coord0);
6. }

Listing 43a: Fragment Shader with Line Numbers

WebGL Beginner's Guide Introduction WebGL Beginner's Guide
Copyright © 2015 Seven Thunder Software. All Rights Reserved.