Hello World, WebGL
Today, we are going to get our feet wet in WebGL to see how we could write a Hello World. Unlike other hello world programs which literally print a hello world on screen, in the graphics world, our hello world is creating a triangle.
Let start with the html. The html is very simple. Declare a canvas element and assign an id to it.
After we get WebGL enabled on our browser, the real part begins. In OpenGL/WebGL there is very critical concept called the shader. There are two kinds of shaders we could control in WebGL. One is the vertex shader and the other one is the fragment shader. This two shaders fit into the beginning and the end of the render pipeline of WebGL. The vertex shader is how we control each vertex in our application. The fragment shader allows us to control the color output on the screen for each pixel. For example, if the resolution of a screen is 1920x1080, then there are 2073600 pixels needs to be draw for every 16.67ms(for keeping our application at 60 fps). What can draw that quickly? That’s why we need the GPU. Most GPUs have hundreds of cores, which allows them to focus on calculation, although their computation abilities are not as good as the CPU. When you are writing shaders, you are actually writing instructions to tell the GPU how to deal with each pixel on the screen. That is one of coolest thing of WebGL!
After we initialize those two shaders, we can start to tell WebGL what we need to draw on the screen. We need to create a buffer first, which stores our vertices positions, along with other information for drawing. This data is used when WebGL issues a request to draw.
One last thing we need to do is actually draw our lovely triangle onto the screen. First, we need to tell WebGL how big the window will be. We use the gl.veiwport() method to do this. Then we create our projection and model view matrices. After that, we pass our position, projection matrix, and model-view matrix to the shader. Finally, we call the gl.drawArrays() method to draw our triangle.
Here is the main step of WebGL calls.
Then you will see something like this. The triangle we just made is Social Tables pink!