Using Texture Maps in WebGL

Using textures in WebGL is also the same as in OpenGL, but handling the loading and setup is much simpler, since HTML lends a helping hand. In fact, loading a texture from a file is a one-line operation. In our demo, we use a single texture named OpenGL-logo.png.

var image = new Image();image.src = "OpenGL-logo.png";

Yes; that’s all there is to loading the pixels from the image into a variable. However, HTML pages load asynchronously, so knowing when the image file has been received and loaded needs to be handled in a callback. Fortunately, JavaScript has a ready-made method in the Image class for handling that situation: onload(). We can specify the onload() method as follows:

image.onload = function () {    configureTexture(image); ...

Get OpenGL Programming Guide: The Official Guide to Learning OpenGL, Version 4.3, Eighth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.