Using Textures in a Shader

Texture coordinates are exposed to the shader code in the same way that they are with any other vertex attribute. We'll want to include a two-element vector attribute in our vertex shader that will map to our texture coordinates:

in vec2 aVertexTextureCoords;

Additionally, we will also want to add a new uniform to the fragment shader that uses a type we haven't seen before: sampler2D. The sampler2D uniform is what allows us to access the texture data in the shader:

uniform sampler2D uSampler;

In the past, when we've used uniforms, we set them to the value that we want them to be in the shader, such as a light color. Samplers work a bit differently. The following code shows how to associate a texture with a specific sampler uniform:

gl.activeTexture(gl.TEXTURE0);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.uniform1i(program.uSampler, 0);

So, what's going on here? First off, we are changing the active texture index with gl.activeTexture. WebGL supports the use of multiple textures at once (which we'll talk about later in this chapter), so it's good practice to specify which texture index we're working with, even though it won't change for the duration of this program. Next, we bind the texture we wish to use, which associates it with the currently active texture, TEXTURE0. Finally, we tell the sampler uniform which texture it should be associated with given the texture unit provided via gl.uniform1i. Here, we give it 0 to indicate that the sampler should use TEXTURE0.

We are now ready to use our texture in the fragment shader! The simplest way to use a texture is to return its value as the fragment color, as shown here:

texture(uSampler, vTextureCoord);

texture takes in the sampler uniform we wish to query and the coordinates to lookup, and returns the color of the texture image at those coordinates as vec4. If the image has no alpha channel, vec4 will still be returned with the alpha component always set to 1.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.120.109