📜 ⬆️ ⬇️

WebGL Beginner's Guide Chapter 1: Getting Started With WebGL

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:

')
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:




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:

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:


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:

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.
  1. 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> 

  2. Save the file as ch1_Canvas.html .
  3. Open this file through a supported browser.
  4. 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 border
This 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 Attributes
In the previous example, there are 3 attributes:

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.
  1. Open the ch1_Canvas.html file in your favorite text editor (ideally, you can choose the syntax for HTML / JavaScript).
  2. 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:
  1. 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: { // 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 decimal cipher //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> 

  2. 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 reviewed
    • clear : 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 .

  3. Open the test_gl_attributes.html file using a supported browser.
  4. Press 1. You will see how the canvas changes its color to green. If you want to know the color used, then press 3.
  5. 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 context
It 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.
  1. Open the ch1_Car.html file in any of the supported browsers
  2. You will see the WebGL scene with the car, as shown below:



  3. 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.
  4. 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.
  5. To achieve the effect that occurs when you press the arrow keys, we use JavaScript timers. We'll talk about animation in chapter 5.
  6. 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:

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 link

Thank you all for your attention!

Source: https://habr.com/ru/post/198306/


All Articles