OpenGL: triangle with white center

Just recently I’ve learned how to create a triangle with OpenGL that has a white center and colored corners. Since I haven’t found a site explaining how to do this I thought about sharing my solution here.

It’s pretty easy as soon as you know that OpenGL blends the color between vertexes horizontally. Just setting the corners of the triangle to the three fundamental colors (RGB) hoping that the center gets white won’t cut it.

The goal

The result should display a triangle with a white center and corners showing different colors. Have a look at it here.



One solution is splitting the triangle into smaller ones. This way you can set the color of the vertex in the center to white – a vertex all three sub-triangles have in common – and change the color of the corners as you see fit.

You can have a look at the code here. Basically, it consists of some boilerplate code for OpenGL and a display function that contains the magic.

I’ve used a GL_TRIANGLE_FAN to construct the triangle. The vertexes are created in this order: center, top, bottom left, bottom right and top again. Right before every vertex definition the color is set like I wanted it.


In the end it’s simple to create a triangle with a white center. I hope this was helpful in understanding how shading works in OpenGL. Note that I’ve commented out a line in the code, try uncommenting it to see how the triangle really looks like.