HTML and CSS Reference
In-Depth Information
Animating the cube
Now that you know a bit about creating an object in WebGL, let's learn about animating the
cubeonthecanvas.Similartowhatwedidinthe2Dcontext,weusethe drawScreen() func-
tion 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
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 ).
Minimum units
The smallest unit size away from our viewport that we want to display ( 0.1 ).
Maximum units
The furthest unit size away from our viewport that we want to see ( 100.0 ).
Next, we move to the center of the 3D scene, calling loadIdentity() so that we can start
drawing. We then call mvTranslate() , passing the locations on the x-, y-, and z-axes to draw
the cube. Torotate the cube, wecall afunction named mvPushMatrix() ,andlater mvPopMat-
rix() , which is similar to how we called context.save() and context.restore() when
rotating objects on the 2D canvas. The call to mvRotate() then makes the cube rotate from
the center, tilted up and to the right:
loadIdentity ();
mvTranslate ([ 0 , 0.0 , 10.0 ]);
Search WWH ::




Custom Search