Time for action – texturing the cube
Open the file ch7_Textured_Cube.html
in your favorite HTML editor. This contains the simple lit cube example from the previous chapter. If you open it in an HTML5 browser, you should see a scene that looks like the following screenshot:
In this example we will add a texture map to this cube as shown here:
First, let's load the texture image. At the top of the script block, add a new variable to hold the texture:
var texture = null;
Then, at the bottom of the
configure
function, add the following code, which creates the texture object, loads an image, and sets the image as the texture data. In this case, we'll use a PNG image with the WebGL logo on it as our texture.//Init texture texture = gl.createTexture(); var image = new Image(); image.onload = function(){ gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); ...