Created
March 29, 2014 04:37
-
-
Save esmitt/9848516 to your computer and use it in GitHub Desktop.
Function to fill a triangle defined by points p1, p2 and p3 using their barycentric coordinates. The functions are made in Javascript, but the porting any language is easily.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function f_ab(x, y, pa, pb) | |
{ | |
return (pa.y - pb.y) * x + (pb.x - pa.x) * y + pa.x*pb.y - pb.x*pa.y; | |
} | |
/// @param context the context of the canvas | |
/// @param p1, p2, p3 The three points of the triangle | |
function drawTriangle(context, p1, p2, p3) | |
{ | |
var bbox = { top: {x: Math.min(p1.x, p2.x, p3.x), y:Math.min(p1.y, p2.y, p3.y)}, | |
right: {x: Math.max(p1.x, p2.x, p3.x), y:Math.max(p1.y, p2.y, p3.y)}}; | |
var x,y; | |
for (y = bbox.top.y; y <= bbox.right.y; y++) | |
{ | |
for (x = bbox.top.x; x <= bbox.right.x; x++) | |
{ | |
var alpha = f_ab(x, y, p2, p3) / f_ab(p1.x, p1.y, p2, p3); | |
var theta = f_ab(x, y, p3, p1) / f_ab(p2.x, p2.y, p3, p1); | |
var gamma = f_ab(x, y, p1, p2) / f_ab(p3.x, p3.y, p1, p2); | |
if(alpha >= 0 && alpha <= 1 && theta >= 0 && theta <= 1 && gamma >= 0 && gamma <= 1) | |
setPixel(context, x, y, 240,190,0,1); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment