HTML and CSS Reference
In-Depth Information
Now you see that points go around in a counterclockwise direction.
But what does it mean when a polygon is “facing you”? It means that the exterior side of the polygon is
facing you. Although it's not obvious when we look at a single triangle, remember that we're talking about
solids in 3D space. In that case, each polygon has one exterior side and one interior side.
There are times when you want to draw the opposite side of the triangle. For example, if the viewport is
located inside a cube and looking out, you want to see the interior sides—the walls, ceiling, and floor. But
for the examples here, looking at a model, you want to view the exterior sides of the geometry that it's
made of.
When determining if a polygon is clockwise or counterclockwise, we refer to the screen positions of the
points—not the 3D x, y, and z positions, but the getScreenX() , getScreenY() position that is the location
on the canvas determined by applying perspective.
You can reverse the setup and make a system where counterclockwise polygons face you, and clockwise
ones faced away. Either way works as long as you are consistent.
So again, we return to the question: How do you determine whether three points are arranged in a
clockwise or counterclockwise direction? It's such an easy thing for your eyes to pick out, but when it
comes to writing it down in code, the problem suddenly seems like an abstract concept.
What you do is add a method to the Triangle class, called isBackface . This evaluates the three points
that make up the triangle, and returns true if they are counterclockwise and false if they are clockwise.
Here is the updated Triangle class with the new method (file triangle.js ). Notice that alpha is set to
1, since we are drawing opaque shapes in this chapter:
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;
}
Triangle.prototype.draw = function (context) {
if (this.isBackface()) {
return;
}
context.save();
context.lineWidth = this.lineWidth;
context.fillStyle = context.strokeStyle = utils.colorToRGB(this.color, this.alpha);
context.beginPath();
context.moveTo(this.pointA.getScreenX(), this.pointA.getScreenY());
context.lineTo(this.pointB.getScreenX(), this.pointB.getScreenY());
context.lineTo(this.pointC.getScreenX(), this.pointC.getScreenY());
context.closePath();
context.fill();
if (this.lineWidth > 0) {
context.stroke();
Search WWH ::




Custom Search