WebGL Textures & Vertices

Beginner's Guide

Page Thirty Nine

Compile Shaders

The method getShader(String, nType) called by getProgram(), returns either a WebGLShader or null. Method getShader(String, nType) first parameter is a String with the id of a script tag from the current Web page. The second parameter is one of two WebGL constants representing the type of shader to compile. The WebGL constants are either VERTEX_SHADER or FRAGMENT_SHADER.

Class GLControl was designed for our series of WebGL books. Some of the other books in the series declare unique shaders in separate Web pages. However WebGL Textures & Vertices: Beginner's Guide only uses the book's default shaders. Therefore eShader = document.getElementById(sID); always returns null for this book's example projects.

If the nType parameter is FRAGMENT_SHADER then the local variable sCode receives a prepared String of fragment shader code. If the nType parameter is VERTEX_SHADER then the local variable sCode receives a prepared String of vertex shader code. The section titled Shader Details discusses each line of the default shaders.

Once we have the shader code, we're ready to create and compile a shader.

WebGL API createShader(type)

The WebGL API method createShader(type) returns an empty WebGLShader object. Pass one of two WebGL constants to createShader(type). For vertex shaders the parameter should equal VERTEX_SHADER. For fragment shaders the parameter should equal FRAGMENT_SHADER.

The controller's method getShader(sID, nType) passes the shader's type through the parameter nType. Therefore nType equals either VERTEX_SHADER or FRAGMENT_SHADER. Method getShader(String, nType) calls the WebGL method createShader(type) as follows.

shader = gl.createShader
( 
 nType
);

Listing 35: WebGL API createShader(type)

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