WebGL global variables

The first thing we are going to do is create a lot of JavaScript global variables. If this code were meant for more than demonstration, using this many global variables is generally frowned upon and considered bad practice. But for what we are doing right now, it helps simplify things:

<script type='text/javascript'>
var gl = null; // WebGLRenderingContext
var program = null; // WebGLProgram
var texture = null; // WebGLTexture
var img = null; // HTMLImageElement
var canvas = null;
var image_width = 0;
var image_height = 0;
var vertex_texture_buffer = null; // WebGLBuffer
var a_texcoord_location = null; // GLint
var a_position_location = null; // GLint
var u_translate_location = null; // WebGLUniformLocation
var u_texture_location = null; // WebGLUniformLocation

The first variable, gl, is the new version of the rendering context. Typically, if you are using a 2D rendering context, you call it ctx, and if you are using a WebGL rendering context, you name it gl. The second line defines the program variable. When we compile the vertex and fragment shaders, we get a compiled version in the form of a WebGLProgram object stored inside of this program variable. The texture variable will hold a WebGLTexture that we will be loading from the spaceship.png image file. That is the image that we used in the previous chapter for the 2D canvas tutorial. The img variable will be used to load the spaceship.png image file that will be used to load the texture. The canvas variable will once again be a reference to our HTML canvas element and image_width, and image_height will hold the height and width of the spaceship.png image once it is loaded.

The vertex_texture_buffer attribute is a buffer that will be used to transfer vertex geometry and texture data to the GPU so that the shader we wrote in the previous section can use it. The a_texcoord_location and a_position_location variables will be used to hold references to the a_texcoord and a_position attribute variables in the vertex shader, and finally, u_translate_location and u_texture_location are used to reference the u_translate and u_texture uniform variables in the shader.