|Getting started with WebGL|
|Written by David Conrad|
Page 3 of 3
In this simple case the only vertex attribute that the shader processes is its position. The shader has a variable called
attribute vec3 vertexPosition;
The whole subject of vertex buffers and arrays is a complicated one. The first step is to get the reference to the attribute in the shader and then enable it for rendering. If you enable it WebGL will use its data when ever you ask for a draw or re-draw of the scene.
var vertexPos = gl.getAttribLocation(
Next we create a buffer object - this is a completely general buffer without any particular structure - and bind it to the WebGL object's array buffer:
var vertexBuffer = gl.createBuffer();
After binding it we need to specify the data structure of the array that will be used to store the data:
The buffer that we have just created is an internal buffer in the sense that WebGL uses it to display whatever vertex data you have transferred to it. It provides a "retained mode" way of working with a 3D model.
Lets draw a single triangle to get started:
var vertices = new Float32Array(
Final setup and drawing
Now we are almost ready do render the model but there are still some very simple initialisation steps we need to take.
The first is to set the values that the color and depth buffer will be cleared to:
gl.clearColor(0.0, 0.0, 0.0, 1.0);
Notice these do not clear either buffer just set the default values that are used by a clear operation.
Next we set the way that "culling" is performed.
This two set the system up to remove pixels that are behind other pixels in the 2D rendered scene - without this you would be able to see distant objects mixed in with closer objects.
Finally we can clear the buffers using the values we just set:
and finally we can ask the system to draw the triangle or in general whatever is in the buffer:
The result is a fairly unimpressive green triangle - but this is a 3D green triangle.
For example, if you change the model view matrix you can see the triangle from different locations. Don't expect any lighting effects or shadows because we haven't used a shader that creates them. Also try modifying the vertex positions of the triangles points and you will soon see that it is 3D.
From here you need to create more sophisticated shaders, use matrix operations to set up the view and position, define more complex models with color and texture attributes, experiment with lighting and animation.
More on using WebGL soon.
|Last Updated ( Wednesday, 04 June 2014 )|