HTML and CSS Reference
In-Depth Information
toward the objects. Once an object has gone behind the viewpoint, replace it way out in the distance. That
way there is a never-ending supply of objects to move past.
The objects we use in the next example are simple, stylized trees with randomized branch positions. This
is the Tree class, which has the 3D position properties and draws a somewhat random stick figure tree.
This code will be file tree.js :
function Tree () {
this.x = 0;
this.y = 0;
this.xpos = 0;
this.ypos = 0;
this.zpos = 0;
this.scaleX = 1;
this.scaleY = 1;
this.color = "#ffffff";
this.alpha = 1;
this.lineWidth = 1;
this.branch = [];
//generate some random branch positions
this.branch[0] = -140 - Math.random() * 20;
this.branch[1] = -30 - Math.random() * 30;
this.branch[2] = Math.random() * 80 - 40;
this.branch[3] = -100 - Math.random() * 40;
this.branch[4] = -60 - Math.random() * 40;
this.branch[5] = Math.random() * 60 - 30;
this.branch[6] = -110 - Math.random() * 20;
}
Tree.prototype.draw = function (context) {
context.save();
context.translate(this.x, this.y);
context.scale(this.scaleX, this.scaleY);
context.lineWidth = this.lineWidth;
context.strokeStyle = utils.colorToRGB(this.color, this.alpha);
context.beginPath();
context.moveTo(0, 0);
context.lineTo(0, this.branch[0]);
context.moveTo(0, this.branch[1]);
context.lineTo(this.branch[2], this.branch[3]);
context.moveTo(0, this.branch[4]);
context.lineTo(this.branch[5], this.branch[6]);
context.stroke();
context.restore();
};
Again, for this example, we use a white on a black background color. The script creates several trees, and
they are spread out randomly on the x-axis, 1,000 pixels in either direction. They are also spread out on
the z-axis, from 0 to 10,000. They all have the same y position though, based on the floor property,
which gives the impression of a ground plane.
The following code is for excercise 08-trees-1.html , and you can see what it looks like in Figure 15-7.
Search WWH ::




Custom Search