# 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!