In 2007, Vladimir Vukicevic, an American-Serbian software engineer, began working on an OpenGL prototype for the then upcoming HTML <canvas>
element which he called Canvas 3D. In March, 2011, his work would lead Kronos Group, the nonprofit organization behind OpenGL, to create WebGL: a specification to grant Internet browsers access to Graphic Processing Units (GPUs) on those computers where they were used.
WebGL was originally based on OpenGL ES 2.0 (ES standing for Embedded Systems), the OpenGL specification version for devices such as Apple's iPhone and iPad. But as the specification evolved, it became independent with the goal of providing portability across various operating systems and devices. The idea of web-based, real-time rendering opened a new universe of possibilities for web-based 3D environments such as videogames, scientific visualization, and medical imaging. Additionally, due to the pervasiveness of web browsers, these and other kinds of 3D applications could be taken to mobile devices such as smart phones and tablets. Whether you want to create your first web-based videogame, a 3D art project for a virtual gallery, visualize the data from your experiments, or any other 3D application you could have in mind, the first step will be always to make sure that your environment is ready.
In this chapter, you will:
Understand the structure of a WebGL application
Set up your drawing area (canvas)
Test your browser's WebGL capabilities
Understand that WebGL acts as a state machine
Modify WebGL variables that affect your scene
Load and examine a fully-functional scene
WebGL is a web-based 3D Graphics API. As such there is no installation needed. At the time this book was written, you will automatically have access to it as long as you have one of the following Internet web browsers:
Firefox 4.0 or above
Google Chrome 11 or above
Safari (OSX 10.6 or above). WebGL is disabled by default but you can switch it on by enabling the Developer menu and then checking the Enable WebGL option
Opera 12 or above
To get an updated list of the Internet web browsers where WebGL is supported, please check on the Khronos Group web page following this link:
http://www.khronos.org/webgl/wiki/Getting_a_WebGL_Implementation
You also need to make sure that your computer has a graphics card.
If you want to quickly check if your current configuration supports WebGL, please visit this link:
WebGL is a 3D graphics library that enables modern Internet browsers to render 3D scenes in a standard and efficient manner. According to Wikipedia, rendering is the process of generating an image from a model by means of computer programs. As this is a process executed in a computer, there are different ways to produce such images.
The first distinction we need to make is whether we are using any special graphics hardware or not. We can talk of software-based rendering, for those cases where all the calculations required to render 3D scenes are performed using the computer's main processor, its CPU; on the other hand we use the term hardware-based rendering for those scenarios where there is a Graphics Processing Unit (GPU) performing 3D graphics computations in real time. From a technical point of view, hardware-based rendering is much more efficient than software-based rendering because there is dedicated hardware taking care of the operations. Contrastingly, a software-based rendering solution can be more pervasive due to the lack of hardware dependencies.
A second distinction we can make is whether or not the rendering process is happening locally or remotely. When the image that needs to be rendered is too complex, the render most likely will occur remotely. This is the case for 3D animated movies where dedicated servers with lots of hardware resources allow rendering intricate scenes. We called this server-based rendering . The opposite of this is when rendering occurs locally. We called this client-based rendering .
WebGL has a client-based rendering approach: the elements that make part of the 3D scene are usually downloaded from a server. However, all the processing required to obtain an image is performed locally using the client's graphics hardware.
In comparison with other technologies (such as Java 3D, Flash, and The Unity Web Player Plugin), WebGL presents several advantages:
JavaScript programming: JavaScript is a language that is natural to both web developers and Internet web browsers. Working with JavaScript allows you to access all parts of the DOM and also lets you communicate between elements easily as opposed to talking to an applet. Because WebGL is programmed in JavaScript, this makes it easier to integrate WebGL applications with other JavaScript libraries such as JQuery and with other HTML5 technologies.
Automatic memory management: Unlike its cousin OpenGL and other technologies where there are specific operations to allocate and deallocate memory manually, WebGL does not have this requisite. It follows the rules for variable scoping in JavaScript and memory is automatically deallocated when it's no longer needed. This simplifies programming tremendously, reducing the code that is needed and making it clearer and easier to understand.
Pervasiveness: Thanks to current advances in technology, web browsers with JavaScript capabilities are installed in smart phones and tablet devices. At the moment of writing, the Mozilla Foundation is testing WebGL capabilities in Motorola and Samsung phones. There is also an effort to implement WebGL on the Android platform.
Performance: The performance of WebGL applications is comparable to equivalent standalone applications (with some exceptions). This happens thanks to WebGL's ability to access the local graphics hardware. Up until now, many 3D web rendering technologies used software-based rendering.
Zero compilation: Given that WebGL is written in JavaScript, there is no need to compile your code before executing it on the web browser. This empowers you to make changes on-the-fly and see how those changes affect your 3D web application. Nevertheless, when we analyze the topic of shader programs, we will understand that we need some compilation. However, this occurs in your graphics hardware, not in your browser.
As in any 3D graphics library, in WebGL, you need certain components to be present to create a 3D scene. These fundamental elements will be covered in the first four chapters of the book. Starting from Chapter 5, Action, we will cover elements that are not required to have a working 3D scene such as colors and textures and then later on we will move to more advanced topics.
The components we are referring to are as follows:
Canvas: It is the placeholder where the scene will be rendered. It is a standard HTML5 element and as such, it can be accessed using the Document Object Model (DOM) through JavaScript.
Objects: These are the 3D entities that make up part of the scene. These entities are composed of triangles. In Chapter 2, Rendering Geometry, we will see how WebGL handles geometry. We will use WebGL buffers to store polygonal data and we will see how WebGL uses these buffers to render the objects in the scene.
Lights: Nothing in a 3D world can be seen if there are no lights. This element of any WebGL application will be explored in Chapter 3, Lights!. We will learn that WebGL uses shaders to model lights in the scene. We will see how 3D objects reflect or absorb light according to the laws of physics and we will also discuss different light models that we can create in WebGL to visualize our objects.
Camera: The canvas acts as the viewport to the 3D world. We see and explore a 3D scene through it. In Chapter 4, Camera, we will understand the different matrix operations that are required to produce a view perspective. We will also understand how these operations can be modeled as a camera.
This chapter will cover the first element of our list—the canvas. We will see in the coming sections how to create a canvas and how to set up a WebGL context.
Using your favorite editor, create a web page with the following code in it:
<!DOCTYPE html> <html> <head> <title> WebGL Beginner's Guide - Setting up the canvas </title> <style type="text/css"> canvas {border: 2px dotted blue;} </style> </head> <body> <canvas id="canvas-element-id" width="800" height="600"> Your browser does not support HTML5 </canvas> </body> </html>
Note
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Save the file as
ch1_Canvas.html
.Open it with one of the supported browsers.
You should see something similar to the following screenshot:
We have just created a simple web page with a canvas in it. This canvas will contain our 3D application. Let's go very quickly to some relevant elements presented in this example.
This is the piece of code that determines the canvas style:
<style type="text/css"> canvas {border: 2px dotted blue;} </style>
As you can imagine, this code is not fundamental to build a WebGL application. However, a blue-dotted border is a good way to verify where the canvas is located, given that the canvas will be initially empty.
If you see the message on your screen: Your browser does not support HTML5 (Which was the message we put between <canvas>
and </canvas>
) then you need to make sure that you are using one of the supported Internet browsers.
If you are using Firefox and you still see the HTML5 not supported message. You might want to be sure that WebGL is enabled (it is by default). To do so, go to Firefox and type about:config
in the address bar, then look for the property webgl.disabled
. If is set to true
, then go ahead and change it. When you restart Firefox and load ch1_Canvas.html
, you should be able to see the dotted border of the canvas, meaning everything is ok.
In the remote case where you still do not see the canvas, it could be due to the fact that Firefox has blacklisted some graphic card drivers. In that case, there is not much you can do other than use a different computer.
A WebGL context is a handle (more strictly a JavaScript object) through which we can access all the WebGL functions and attributes. These constitute WebGL's Application Program Interface (API).
We are going to create a JavaScript function that will check whether a WebGL context can be obtained for the canvas or not. Unlike other JavaScript libraries that need to be downloaded and included in your projects to work, WebGL is already in your browser. In other words, if you are using one of the supported browsers, you don't need to install or include any library.
We are going to modify the previous example to add a JavaScript function that is going to check the WebGL availability in your browser (trying to get a handle). This function is going to be called when the page is loaded. For this, we will use the standard DOM onLoad
event.
Open the file
ch1_Canvas.html
in your favorite text editor (a text editor that highlight HTML/JavaScript syntax is ideal).Add the following code right below the
</style>
tag:<script> var gl = null; function getGLContext(){ var canvas = document.getElementById("canvas-element-id"); if (canvas == null){ alert("there is no canvas on this page"); return; } var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"]; for (var i = 0; i < names.length; ++i) { try { gl = canvas.getContext(names[i]); } catch(e) {} if (gl) break; } if (gl == null){ alert("WebGL is not available"); } else{ alert("Hooray! You got a WebGL context"); } } </script>
We need to call this function on the
onLoad
event. Modify your body tag so it looks like the following:<body onLoad ="getGLContext()">
Save the file as
ch1_GL_Context.html.
Open the file
ch1_GL_Context.html
using one of the WebGL supported browsers.If you can run WebGL you will see a dialog similar to the following:

Using a JavaScript variable (gl
), we obtained a reference to a WebGL context. Let's go back and check the code that allows accessing WebGL:
var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"]; for (var i = 0; i < names.length; ++i) { try { gl = canvas.getContext(names[i]); } catch(e) {} if (gl) break; }
The canvas getContext
method gives us access to WebGL. All we need to specify a context name that currently can vary from vendor to vendor. Therefore we have grouped them in the possible context names in the names
array. It is imperative to check on the WebGL specification (you will find it online) for any updates regarding the naming convention.
getContext
also provides access to the HTML5 2D graphics library when using 2d
as the context name. Unlike WebGL, this naming convention is standard. The HTML5 2D graphics API is completely independent from WebGL and is beyond the scope of this book.
A WebGL context can be understood as a state machine: once you modify any of its attributes, that modification is permanent until you modify that attribute again. At any point you can query the state of these attributes and so you can determine the current state of your WebGL context. Let's analyze this behavior with an example.
In this example, we are going to learn to modify the color that we use to clear the canvas:
Using your favorite text editor, open the file
ch1_GL_Attributes.html
:<html> <head> <title> WebGL Beginner's Guide - Setting WebGL context attributes </title> <style type="text/css"> canvas {border: 2px dotted blue;} </style> <script> var gl = null; var c_width = 0; var c_height = 0; window.onkeydown = checkKey; function checkKey(ev){ switch(ev.keyCode){ case 49:{ // 1 gl.clearColor(0.3,0.7,0.2,1.0); clear(gl); break; } case 50:{ // 2 gl.clearColor(0.3,0.2,0.7,1.0); clear(gl); break; } case 51:{ // 3 var color = gl.getParameter(gl.COLOR_CLEAR_VALUE); // Don't get confused with the following line. It // basically rounds up the numbers to one decimalcipher //just for visualization purposes alert('clearColor = (' + Math.round(color[0]*10)/10 + ',' + Math.round(color[1]*10)/10+ ',' + Math.round(color[2]*10)/10+')'); window.focus(); break; } } } function getGLContext(){ var canvas = document.getElementById("canvas-element-id"); if (canvas == null){ alert("there is no canvas on this page"); return; } var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"]; var ctx = null; for (var i = 0; i < names.length; ++i) { try { ctx = canvas.getContext(names[i]); } catch(e) {} if (ctx) break; } if (ctx == null){ alert("WebGL is not available"); } else{ return ctx; } } function clear(ctx){ ctx.clear(ctx.COLOR_BUFFER_BIT); ctx.viewport(0, 0, c_width, c_height); } function initWebGL(){ gl = getGLContext(); } </script> </head> <body onLoad="initWebGL()"> <canvas id="canvas-element-id" width="800" height="600"> Your browser does not support the HTML5 canvas element. </canvas> </body> </html>
You will see that this file is very similar to our previous example. However, there are new code constructs that we will explain briefly. This file contains four JavaScript functions:
Function
Description
This is an auxiliary function. It captures the keyboard input and executes code depending on the key entered.
Similar to the one used in the Time for action – accessing the WebGL context section. In this version, we are adding some lines of code to obtain the canvas' width and height.
Clear the canvas to the current clear color, which is one attribute of the WebGL context. As was mentioned previously, WebGL works as a state machine, therefore it will maintain the selected color to clear the canvas up to when this color is changed using the WebGL function
gl.clearColor
(See thecheckKey
source code)This function replaces
getGLContext
as the function being called on the documentonLoad
event. This function calls an improved version ofgetGLContext
that returns the context in thectx
variable. This context is then assigned to the global variablegl
.Open the file
test_gl_attributes.html
using one of the supported Internet web browsers.Press 1. You will see how the canvas changes its color to green. If you want to query the exact color we used, press 3.
The canvas will maintain the green color until we decided to change the attribute clear color by calling
gl.clearColor
. Let's change it by pressing 2. If you look at the source code, this will change the canvas clear color to blue. If you want to know the exact color, press 3.
In this example, we saw that we can change or set the color that WebGL uses to clear the canvas by calling the clearColor
function. Correspondingly, we used getParameter(gl.COLOR_CLEAR_VALUE)
to obtain the current value for the canvas clear color.
Throughout the book we will see similar constructs where specific functions establish attributes of the WebGL context and the getParameter
function retrieves the current values for such attributes whenever the respective argument (in our example, COLOR_CLEAR_VALUE
) is used.
Once you finish reading the book you will be able to create scenes like the one we are going to play with next. This scene shows one of the cars from the book's virtual car showroom.
Open the file
ch1_Car.html
in one of the supported Internet web browsers.You will see a WebGL scene with a car in it as shown in the following screenshot. In Chapter 2, Rendering Geometry we will cover the topic of geometry rendering and we will see how to load and render models as this car.
Use the sliders to interactively update the four light sources that have been defined for this scene. Each light source has three elements: ambient, diffuse, and specular elements. We will cover the topic about lights in Chapter 3, Lights!.
Click and drag on the canvas to rotate the car and visualize it from different perspectives. You can zoom by pressing the Alt key while you drag the mouse on the canvas. You can also use the arrow keys to rotate the camera around the car. Make sure that the canvas is in focus by clicking on it before using the arrow keys. In Chapter 4, Camera we will discuss how to create and operate with cameras in WebGL.
If you click on the Above, Front, Back, Left, or Right buttons you will see an animation that stops when the camera reaches that position. For achieving this effect we are using a JavaScript timer. We will discuss animation in Chapter 5, Action.
Use the color selector widget as shown in the previous screenshot to change the color of the car. The use of colors in the scene will be discussed in Chapter 6, Colors, Depth Testing, and Alpha Blending. Chapters 7-10 will describe the use of textures (Chapter 7, Textures), selection of objects in the scene (Chapter 8, Picking), how to build the virtual car show room (Chapter 9, Putting It All Together) and WebGL advanced techniques (Chapter 10, Advanced Techniques).
We have loaded a simple scene in an Internet web browser using WebGL.
This scene consists of:
A canvas through which we see the scene.
A series of polygonal meshes (objects) that constitute the car: roof, windows, headlights, fenders, doors, wheels, spoiler, bumpers, and so on.
Light sources; otherwise everything would appear black.
A camera that determines where in the 3D world is our view point. The camera can be made interactive and the view point can change, depending on the user input. For this example, we were using the left and right arrow keys and the mouse to move the camera around the car.
There are other elements that are not covered in this example such as textures, colors, and special light effects (specularity). Do not panic! Each element will be explained later in the book. The point here is to identify that the four basic elements we discussed previously are present in the scene.
In this chapter, we have looked at the four basic elements that are always present in any WebGL application: canvas, objects, lights, and camera.
We have learned how to add an HTML5 canvas to our web page and how to set its ID, width, and height. After that, we have included the code to create a WebGL context. We have seen that WebGL works as a state machine and as such, we can query any of its variables using the getParameter
function.
In the next chapter we will learn how to define, load, and render 3D objects into a WebGL scene.