Hello!
I want to start a free translation of the excellent book
“WebGL Beginner's Guide” , which, in my opinion, will be interesting not only for beginners, but also for more advanced developers.
Content:
- Chapter 1: Getting Started With WebGL
- Chapter 2: Geometry Rendering
- Chapter 3: Lighting
- Chapter 4: Camera
- Chapter 5: Movement
- Chapter 6: Color, Depth, and Alpha Blending
- Chapter 7: Textures
- Chapter 8: Choice
- Chapter 9: Putting It All Together
- Chapter 10: Advanced Methods
')
WebGL was originally based on OpenGL ES 2.0 (ES stands for Embedded Systems), a version of the OpenGL specification for devices such as Apple's iPhone and iPad. But the specification developed, became independent, its main goal is to ensure portability between different operating systems and devices. The idea of a web interface, real-time rendering opened up a new universe of possibilities for 3D web environments such as video games, scientific and medical visualization. In addition, due to the widespread use of web browsers, these and other types of 3D applications can be run on mobile devices, such as smartphones and tablets. If you want to create your first web-based video game, 3D art project for a virtual gallery, visualization of your experiments or any other 3D application, you should keep in mind that the first step should be that you need to make sure that you have suitable medium.
In this chapter you can:
- Understand the structure of a WebGL application
- Create your own drawing areas
- Check your browser's WebGL capabilities
- Understand how the WebGL state machine works
- Modify WebGL variables that affect your scene.
- Download and explore full-featured scenes
System requirements
WebGL is a web based API for 3D graphics. As such, it does not require installation. At the time this book was written, you could automatically work with WebGL if you have one of the following Internet browsers installed:
- Firefox 4.0 or later
- Google Chrome 11 or later
- Safari (OSX 10.6 or later). By default, WebGL is disabled, but you can enable it by setting the Enable WebGL option in the Developer menu.
- Opera 12 or later
To get an updated list of web browsers that support WebGL, click on the following
link . You should also make sure that you have a video card on your computer. If you want to quickly check if your configuration supports WebGL, then follow this
link .
What is WebGL
WebGL is a 3D graphics library that allows modern Internet browsers to render 3D scenes in a standard and efficient way. According to Wikipedia, rendering is the visualization of the process of creating an image from a model using a computer program. Since this process is performed on a computer, there are various ways of obtaining such images.
The first difference we have to make is whether we use any special graphics hardware or not. We can talk about software rendering, in cases where all the calculations necessary for rendering 3D scenes are performed using the main processor of the computer; on the other hand, we use the term hardware rendering, in cases where there is a graphics processor (GPU) for calculating 3D graphics in real time. From a technical point of view, hardware rendering is much more efficient than software, because there are specialized hardware components that handle operations. But, on the other hand, software rendering is usually more common due to the lack of hardware dependencies.
The second difference we can make is whether the rendering process happens locally or remotely. When the image to be displayed is complex, then rendering will most likely occur remotely. This is a case of 3D animated films, when dedicated servers with a large amount of hardware resources allow rendering complex scenes. We will call this server rendering. The opposite of this is rendering that runs locally. We will call this client rendering.
WebGL has a customer-centric approach; the elements that make up part of a 3D scene are usually downloaded from the server. However, all further processing required to obtain the image is performed locally, using the client’s graphics hardware.
Compared to other technologies (for example, Java 3D, Flash and the Unity Web Player Plugin), WebGL has several advantages:
- JavaScript programming: JavaScript is the “native” language for web developers and web browsers. Working with JavaScript allows access to all DOM elements, as well as easy to handle them, as opposed to communicating with applets. Since WebGL is programmed in JavaScript, this makes it easy to integrate WebGL applications with other JavaScript libraries, such as jQuery and other HTML5 technologies.
- Automatic memory management: unlike its fellow OpenGL and other technologies, where there are specific operations for allocating and freeing memory manually, WebGL does not need it. From this it follows that when the JavaScript variable goes out of scope, the memory occupied by it is automatically released. This makes programming extremely easy, reduces the amount of code, makes it more clear and understandable.
- Permeability: thanks to modern technological advances, web browsers with JavaScript support are installed on smartphones and tablet devices. At the time of writing, the Mozilla Foundation is a program to test WebGL capabilities in Motorola and Samsung phones. There is a similar development support for WebGL for the Android platform.
- Performance: WebGL application performance is comparable to equivalent stand-alone applications (with some exceptions). This is due to the ability of WebGL to have access to local graphics hardware accelerators. Until now, many web technologies for 3D rendering use software rendering.
- Zero compilation: Considering that WebGL is written in JavaScript, there is no need to precompile the code before executing it in a web browser. This allows you to make changes on the fly and see how these changes affect the 3D web application. However, when we touch on the topic of shaders, we will realize that we need some compilation. However, this is done using our graphics hardware, not in our browser.
WebGL application structure
As with any 3D graphics library, WebGL requires the presence of certain components to create 3D scenes. These basic elements will be discussed in the first four chapters of the book. Starting from Chapter 5, we will look at elements that are not related to working with a 3D scene, such as colors and textures, and then, later, we will move on to more complex topics.
The elements to which we refer are as follows:
- Canvas: this is the placeholder where the scene will be displayed. This is a standard HTML5 element that 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 made up of triangles. In the second chapter, we will see how WebGL handles geometry. We will use WebGL buffers to store polygons and see how WebGL uses buffers to render objects on the scene.
- Light: nothing in the 3D world can be seen if there are no light sources. This element of any WebGL application will be discussed in Chapter 3. We learn that WebGL uses shaders to simulate light on the stage. We will also see how 3D objects reflect and absorb light in accordance with the laws of physics, and also discuss other light models that we can create in WebGL to visualize our objects.
- Camera: acts as a canvas for viewing the 3D world. Let's see how it can be used to explore the 3D scene. In chapter 4, various matrix operations that are necessary for obtaining a perspective view will be considered. We will also understand how these operations can simulate camera behavior.
This chapter is devoted to the first item in our list, canvas. In the next sections, we will see how to create a canvas and how to set up a WebGL context.
Create HTML5 canvas
Let's create a web page and add HTML5 canvas. Canvas is a rectangular element on a web page where a 3D scene will be displayed.
- Using your favorite editor, create a web page with the following content:
<!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>
- Save the file as
ch1_Canvas.html
. - Open this file through a supported browser.
- You should see something like this:

What just happened?We have just created a simple web page with the canvas contained in it. This canvas will contain our 3D applications. Let's take a look at some of the important elements presented in this example.
Defining CSS style for borderThis is the piece of code that defines the canvas style:
<style type="text/css"> canvas {border: 2px dotted blue;} </style>
As you can imagine, this code is not fundamental to building WebGL applications. However, the blue dotted line is a good way to check where the canvas is, given that the canvas will initially be empty.
Understanding Canvas AttributesIn the previous example, there are 3 attributes:
- Id: is the canvas ID in the Document Object Model (DOM)
- Width and height: these two attributes determine the size of our canvas. When these two attributes are missing, Firefox, Chrome, and WebKit will by default use the 300x150 canvas.
What if the canvas is not supported?If you see a message on the screen:
Your browser does not support HTML5
(which was written between the tags and), then you should make sure that you are using a browser that supports WebGL.
If you are using Firefox and still see the HTML5 not supported message, then check that WebGL support is enabled. To do this, type in the address bar
about:config
, and then look at the
webgl.disabled
property. If set to
true
go and change. When you restart Firefox and load ch1_Canvas.html, you should see the dotted lines of the canvas, that is, everything is in order.
When connecting remotely, if you do not see the canvas, this may be due to the fact that Firefox has blacklisted some graphics card drivers. In this case, nothing remains, how to use another computer.
Access to context webgl
The WebGL context is a descriptor (more precisely, a JavaScript object) through which we can access all the functions and attributes of WebGL. They make up the Application Program Interface WebGL (API).
We are going to create a JavaScript function that will check whether the WebGL context can be obtained on the canvas. Unlike other JavaScript libraries that need to be loaded and connected to a working project, WebGL is already in your browser. In other words, if you are using one of the supported browsers, then you do not need to install and include any library.
We are going to change the previous example by adding a JavaScript function that will check for WebGL support in your browser (try to get a handle). This function will be called when the page loads. For this we will use the standard DOM
onLoad
event.
- Open the
ch1_Canvas.html
file in your favorite text editor (ideally, you can choose the syntax for HTML / JavaScript). - Add the following code directly below the tag.
We need to call this function on the
onLoad
event. Change the content of the
body
tag to the following:
<body onLoad ="getGLContext()">
Save the
ch1_GL_Context.html
file.
Open the
ch1_GL_Context.html
file using one of the browsers that support WebGL.
If you cannot launch WebGL, you will see something like the following dialog:
What just happened?Using the JavaScript variable (gl), we got a link to the WebGL context. Let's go back and check the code that allows access to the 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
getContext
canvas
getContext
gives us access to WebGL. All we need is to specify the name of the context, which may be different from different manufacturers. Therefore, we have grouped all possible context names in the names array. It is extremely important to check the WebGL specification (you can find it on the Internet) for any changes regarding the naming convention.
getContext
can also provide access to HTML5 2D graphics when using a 2D library, depending on the context name. Unlike WebGL, this naming convention is standard. The HTML5 2D Graphics API is completely independent of WebGL and is beyond the scope of this book.
WebGL State Machine
The context of WebGL can be understood as a state machine: as soon as you change any of its attributes, the modification will retain its state until you change the value of the attribute again. At any time, you can query the status of these attributes, so you can determine the current state of your WebGL context. Let's analyze this behavior by example.
In this example, we are going to learn how to change the color we use to clear the canvas:
- Using your favorite text editor, open the
ch1_GL_Attributes.html
file:
<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: { </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 can see that this file is very similar to our previous example. Nevertheless, new designs appear, which we briefly explain. This file contains 4 javascript functions:
checkKey
: is a helper function. It captures keyboard input and executes code depending on the command entered.getGLContext
: similar to the one we have already reviewedclear
: clears the canvas with the current color, which is one of the attributes of the WebGL context. As mentioned earlier, WebGL works as a state machine, so it will maintain the selected color to clear the canvas before that color is changed using the gl.clearColor
function.initWebGL
: this function can replace the getGLContext
function as a function that is called on the document's getGLContext
event. This function calls an improved version of getGLContext
, which returns the context to the ctx
variable. This context is then assigned to the global variable gl
.
- Open the
test_gl_attributes.html
file using a supported browser. - Press 1. You will see how the canvas changes its color to green. If you want to know the color used, then press 3.
- The canvas is green until we decide to change the cleaning color by calling the
gl.clearColor
function. Let's change it by pressing 2. If you look at the code, you can see that the color changes to blue. If you want to know what color it is, press 3.
What just happened?In this example, we saw how we can change and set the color that WebGL uses to clear the canvas by calling the
clearColor
function. Accordingly, we used the
getParameter (gl.COLOR_CLEAR_VALUE)
function
getParameter (gl.COLOR_CLEAR_VALUE)
to get the current color value of the canvas fill.
Throughout the book, we will see similar constructions when specific functions set context attributes, and the WebGL function
getParameter
retrieves the current value of the attributes depending on the argument passed (in our example, this is
COLOR_CLEAR_VALUE
).
Access the WebGL API using contextIt is also important to note that all WebGL functions are available through the WebGL context. In our examples, the context is in the variable
gl
. Thus, any WebGL API call will be made using this variable.
Loading a 3D scene
So far, we have seen how to get and set the context of WebGL; The next step is to discuss objects, lighting and camera. However, why should we wait to look at the possibilities of WebGL? In this section, we will look at how the WebGL scene looks.
Virtual car dealership
Thanks to the book, we will develop a virtual car dealership application using WebGL. For now, we will upload one simple scene to the canvas. This scene will contain a car, several light sources and a camera.
After reading the book, you will be able to create scenes like the one we will create.
- Open the
ch1_Car.html
file in any of the supported browsers - You will see the WebGL scene with the car, as shown below:

- Using the slider, you can interactively update the four lights that are defined for this scene. Each light source consists of three elements: the environment, diffuse and mirror elements. We will discuss the topic of lighting in more detail in Chapter 3.
- Click and drag on the canvas to rotate the car and visualize it from different sides. You can enlarge it by pressing the Alt key while dragging the mouse on the canvas. You can also use the arrow keys to rotate the camera around the car. Make sure the canvas is in focus by clicking on it before using the arrow keys. In Chapter 4, we will look at how to create and work with the camera in WebGL.
- To achieve the effect that occurs when you press the arrow keys, we use JavaScript timers. We'll talk about animation in chapter 5.
- Use the color picker as shown in the previous screenshot to change the color of the car. The use of colors will be discussed in Chapter 6. Chapters 7-10 will describe the use of textures, the selection of objects on the scene, how to build a virtual car dealership, and advanced WebGL methods, respectively.
What just happened?We loaded a simple scene into a web browser using WebGL.
This scene consists of:
- Holst, with which we see the scene
- Several polygons (objects), which are parts of the car: the roof, windows, headlights, wings, doors, wheels, spoilers, bumpers and so on.
- Light sources, otherwise everything would be black
- The camera that defines our position in the 3D world. The camera may be interactive, that is, the position of the observer may vary, depending on user input. In this example, we used 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 lighting effects (specularity). Do not panic! Later all elements will be considered in more detail.
Summary
In this chapter, we looked at four main elements that are always present in any WebGL application: canvas, object, light, and camera.
We learned how to add an HTML5 canvas to a web page, how to set its ID, width and height. After that, we wrote the code that created the WebGL context. We saw that WebGL works as a state machine, as such, we can query any of our variables using the getParameter function.
In the next chapter, we will learn how to define, load, and draw a 3D model in the WebGL scene.
Resources for this article you can download
linkThank you all for your attention!