HTML and CSS Reference
In-Depth Information
Or, you can create a light with a particular position and location like this:
var light = new Light(100, 200, 300, 0.5);
Two things are important here. The distance between the object and light position has no affect on how
brightly the object is lit. The coordinates of the light are used only to calculate the angle that the light ray
bounces off the object and into the viewpoint for us to see it. Because the strength of the light you are
creating does not fall off with distance, changing the x, y, and z to -1,000,000 or down to -1 makes no
difference to the object brightness. Only the brightness property changes that characteristic of the light.
You can certainly add this functionality, altering the brightness value based on the distance from the light
to the area it is hitting, but that exercise is left to you.
Also, brightness must be a number from 0.0 to 1.0. If you go outside of that range, you can wind up with
some odd results from the forthcoming calculations. This is something you can play around with, but for
more realistic lighting effects, you want to stay within this range. For this reason, the brightness property
is adjusted using the method setBrightness . This enables us to validate the number that is passed in, to
make sure it falls within the specified range; this is known as clamping the light.
Now, the light source changes the brightness of the color of a triangle, based on the angle of the light that
is falling on that polygon. If the polygon is facing directly at the light, it displays the full value of its color. As
it turns away from the light, it gets darker and darker. Finally, when it is facing in the opposite direction of
the light source, it is completely in shadow and colored black.
Because Triangle objects keep track of their own color and know how to draw themselves, each triangle
also needs access to this light to perform calculations in its drawing function. So, in the Triangle
constructor, give it a light property:
function Triangle (a, b, c, color) {
this.pointA = a;
this.pointB = b;
this.pointC = c;
this.color = (color === undefined) ? "#ff0000" : utils.parseColor(color);
this.lineWidth = 1;
this.alpha = 1;
this.light = null;
}
Then in the main script, assign each triangle a reference to the light object that we created:
triangles.forEach(function (triangle) {
triangle.light = light;
});
Now, each Triangle object requires a way to look at its base color and the angle and brightness of the
light, and return an adjusted color. Here is that method:
Triangle.prototype.getAdjustedColor = function () {
var color = utils.parseColor(this.color, true),
 
Search WWH ::




Custom Search