Game Development Reference
In-Depth Information
gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s,
vTextureCoord.t));
}
</script>
In the
initShaders
function, the new variable we have added is
textureCoordAttribute
. It references the
aTextureCoord
attribute of the vertex
shader, as shown in the following code:
function initShaders() {
...
shaderProgram.textureCoordAttribute =
gl.getAttribLocation(shaderProgram, "aTextureCoord");
gl.enableVertexAttribArray(shaderProgram.textureCoordAttribute);
...
}
The
createTexture()
function creates the texture reference. To actually create the
texture object itself, you must bind it to the current texture context. We do that after we
load the texture. We create the image object and once the image is loaded, the
onload
event invokes
handleTextureLoaded
. We then bind the texture to actually create the
object using the
bindTexture
function. This function also makes the texture object
the current active texture buffer. The
texImage2D
function loads the texture in GPU
memory and associates it with the active texture object. The
texImage2D
function loads
the
img
object at level of detail
0
(mipmap level), and we specify the input texture
format,
gl.RGBA
, and the storage format. The next call,
texParameteri
, defines the
filter mode for our texture. We use the nearest-neighbor interpolation algorithm to
filter for magnification and minification. Then, we invoke the
drawscenedrawScene
function, as shown in the following code:
function initTextures() {
texture = gl.createTexture();
image = new Image();
// Assigning onLoad Event before setting the source, since the
//onload will never be invoked if we assign the source earlier.
image.onload = function() {
handleTextureLoaded(image, texture);}
image.src = "cubetexture.png";
}
function handleTextureLoaded(img, texture) {
gl.bindTexture(gl.TEXTURE_2D, texture);