WebGL Textures

Carlos Eduardo González Alvarez
cegonzalez13
Published in
2 min readApr 11, 2018

This WebGL Example will focus on attaching textures to 3D objects such as cylinders, cones and spheres, simulating that they are a can of coke, a hershey kiss and a soccer ball, respectively. The source code can be found here:

For this exercise we will only focus on the changes we made for our primitives to look like the textures we apply on them. So, the first thing we are going to do is change our fragment and vertex shaders so they render the textures according to their coordinates for each object we have:

We see that the color of the fragment now relates to the colors of the texture that we are loading. Now when we set our texture coordinates for every object we can get the result we want in no time.

Now, we need to set the textures for our buffers according to the image we pass as a parameter. This can be done by the loadTexture that we define here:

As we can see, the function is in charge of loading the image from the internet or from the file system and convert it into a map of mips for its usage as a texture from the vertex Shader. In order to do this, it has to first set a generic color to the object so it can render this while the image is loading, then it has to create the mip map and replace the colors of the object with the ones found in the image.

We will use the loadTexture function on every object so it can render its own texture of the image we selected:

Finally, we load the textures when we execute the drawScene function, so it will ask for the texture that’s already loaded on every frame.

Every object will have its own drawScene function where they bind the texture to the buffer of the object like this:

Time Log

And thats it… we now have a can of coke, a soccer ball and a hershey kiss floating around in a WebGL Animation. It took me 7 hours to do it instead of 5 which is what i had estimated because I needed to create the primitives from scratch and find out how to add a diferent texture to each one of them.

--

--