Here is a snippet of code from my P4 implementation. This takes an array of triangles and sorts them. Notice that for each triangle, I have already computed a “sum of the Z values” of its 3 vertices (this is the average, but not divided by 3).
this.triangles.sort(function (a, b) { if (a.zsum > b.zsum) { return -1; } else { return 1; } });
Notice that JavaScript arrays have a handy sort function. It takes an optional argument that lets me define a comparison function (this is a lot like C++ or Python’s sort function). You might want to look it up on the web.
And something that came up in office hours today…
If you compute the color for the triangle, when you draw it you need to specify the “fillstyle” – the easiest is to make a string like “rgb(255,100,100)” – but be careful. If you use floating point numbers, it doesn’t work. (I totally spaced on this, but when I look at my code, I see I did take care of this)
var color = "rgb("+Math.round(r)+","+Math.round(g)+","+Math.round(b)+")";