4.1 Cube3D

  Launch example    View color-coded source

The most simple example: A spinning three dimensional cube.
It is neither interactive nor very cute - but an easy way to start ...

Point3D
A model such as the cube consists of Point3Ds, each represents a single point in the space.
See also 2.1 Points & Vectors and 5.1 3dhtml # Point3D.
// the cube model
return new Array(
	//  Point3D( x,  y,  z, m)
	new Point3D( 1,  1,  1, 0),
	new Point3D( 1,  1, -1, 0),
	new Point3D( 1, -1,  1, 0),
	new Point3D( 1, -1, -1, 0),
	new Point3D(-1,  1,  1, 0),
	new Point3D(-1,  1, -1, 0),
	new Point3D(-1, -1,  1, 0),
	new Point3D(-1, -1, -1, 0)
);
Model
The models are the objects in your 3D space. You can move, scale and rotate a model.
See also 5.1 3dhtml # Model.
// creates cube model with name and (a simple) material
var cubeModel = new Model("cube", new Material("°"));
If you want to use the model not only as value storage but as 3D object you must insert the call of model.createPointCode() within the body.
<body>
	<script language="JavaScript" type="text/javascript">
	<!--
	// creates the HTML code representing the model's points
	// NB: This is written directly into the page from within the method	
	cubeModel.createPointCode();
	// -->
	</script>
</body>
After that and the onLoad of the page you can draw the model the first time.
Try it with this method: model.draw().

Transformation
To be able to move, scale and rotate the models as promised you will need transformations (2.3 Transformations). And transformations need matrices (2.2 Matrices).

To create an animation just transform the model multiple times. The easiest way to do so is to call the function that transforms the model at a certain interval. In the code below, this is done with the animate() function, which is initially called from the onLoad-handler once everything's set up and ready to go

It then transforms the point and queues a setTimeout() event calling itself, this will cause the animate() function to loop continously.

// the matrix to transform the model with
var staticRotationMatrix = new Matrix();
staticRotationMatrix.rotateX(0.05);
staticRotationMatrix.rotateY(0.1);

/*
 * The main animate method. Calls itself repeatedly.
 */
function animate() {
	var delay = 10;
	
	// animates cube model ----------------------------------------

	// rotates the cube
	cubeModel.transform(staticRotationMatrix);
	
	// updates display
	cubeModel.draw();
	
	// calls itself with an delay to decouple client computer speed from the animation speed.
	// result: the animation is as fast as possible.
	setTimeout("animate()", delay);
}
Links