40
[0.9, 0.0, 0.0, 1.0], // Back face
[0.6, 0.6, 0.6, 1.0], // Top face
[0.6, 0.0, 0.0, 1.0], // Bottom face
[0.3 ,0.0, 0.0, 1.0], // Right face
[0.3, 0.3, 0.3, 1.0], // Left face
];
The Vertex Index buffer is kind of like a map that builds the object (our cube) based on
the colors specified in Vertex Color (the order of these elements) and the vertices speci‐
fied in the Vertex Position buffer. Each of these sets of three values represents a triangle
that will be drawn onto the 3D context:
webGLContext.bindBuffer(webGLContext.ELEMENT_ARRAY_BUFFER, cubeVertexIndexBuffer);
var cubeVertexIndices = [
0, 1, 2, 0, 2, 3, // Front face
4, 5, 6, 4, 6, 7, // Back face
8, 9, 10, 8, 10, 11, // Top face
12, 13, 14, 12, 14, 15, // Bottom face
16, 17, 18, 16, 18, 19, // Right face
20, 21, 22, 20, 22, 23 // Left face
]
Again, there is more code in initBuffers() than we described here, but start with these
three sections when you want to play with the code and make your own objects.
Animating the cube
Now that you know a bit about creating an object in WebGL, let’s learn about animating
the cube on the canvas. Similar to what we did in the 2D context, we use the
drawScreen() function to position, draw, and animate objects in the 3D context. The
first thing we do here is set up the viewport, which defines the canvas’s view of the 3D
scene. Next, we clear the canvas and then set up the perspective:
function drawScreen() {
webGLContext.viewport(0, 0, webGLContext.viewportWidth,
webGLContext.viewportHeight);
webGLContext.clear(webGLContext.COLOR_BUFFER_BIT |
webGLContext.DEPTH_BUFFER_BIT);
perspective(25, (webGLContext.viewportWidth / webGLContext.viewportHeight),
0.1, 100.0);
The perspective has four parameters:
Field of view
The angle at which we will view the 3D scene (25 degrees).
Width-to-height ratio
The radio of width to height of the current size of the canvas (500×500).
3D with WebGL | 627