# Fill Triangle Block

How can I create a function to draw a triangle on an image then fill it?

2 Likes

Ah, this is actually a pretty difficult task! Youâ€™ll want to look up a â€śtriangle rasterizationâ€ť algorithm

1 Like

Would a right triangle be easier?

Yes, if the triangle is half of an unrotated rectangle. Off the top of my head, it would probably look something like this:

1. Figure out which two points form the hypotenuse (itâ€™ll be the two points that do not share an x or a y value)
2. Use the bresenham line algorithm to draw the line between those two points
3. At the point in that algorithm where you set the pixel, instead draw a vertical line. The line should start at the pixel position and go vertically to the y of the third (non-hypotenuse) point

Thereâ€™s probably a smarter way to do it but thatâ€™s what iâ€™ve got!

Hereâ€™s an implementation that uses that algorithm:

Note that this does not actually check that the three points are a right triangle, Iâ€™ll leave that to you

Also this doesnâ€™t work for rotated triangles!