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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.