How to add colour to an object in OpenGL

Back to OpenGL Tutorial Index

In this OpenGL tutorial you will learn how to color your OpenGL shapes. In this color tutorial I will be once again working with an OpenGL square created using the same glVertex3f positions as in the last tutorial on creating the square.

Now that we are able to display objects on the screen. They don't look too
flash if everything is the same colour. So we want to be able to change
the colour of our current objects.

Now this is easy enough. There is a function you can call that looks like:
glColor3f(1.0, 0.0, 0.0);
This allows you to set the colour of the object to be drawn to the values
of R(ed),G(reen),B(lue) where I have R set to 1, which is the maximum,
G is set to 0 and B is also set to 0.

So here the highest value you can have for a colour is 1, and the lowest
is 0. If you were to vary it to:
glColor3f(0.0, 1.0, 0.0);
We now have no red, full green, and no blue. So this would create
a green object.

The colours can also be varied, for example:
glColor3f(0.0, 0.0, 0.0);
Wouls come out as black as there is no colour, and
glColor3f(1.0, 1.0, 1.0);
Would come out as white as it is using each colour fully.

So here "glColor3f(1.0, 0.0, 0.0);" will come out as a red object.

There is also another function that takes four parameters (RGBA) but I will
show you that in the Blending tutorial. As it involves a completely new
method.

Just keep in mind that these colours will not work while you have lighting
effects enabled unless you call:
glEnable(GL_COLOR_MATERIAL);

If you have any questions on this, please email me at swiftless@gmail.com

#include <GL/gl.h>
#include <GL/glut.h>

void square (void) {
glColor3f(1.0, 0.0, 0.0); //this will set the square to red.
glBegin(GL_QUADS);
glVertex3f(-0.5, -0.5, 0.0);
glVertex3f(-0.5, 0.5, 0.0);
glVertex3f(0.5, 0.5, 0.0);
glVertex3f(0.5, -0.5, 0.0);
glEnd();
}

void display (void) {
glClearColor (0.0,0.0,0.0,1.0);
glClear (GL_COLOR_BUFFER_BIT);
glLoadIdentity();
gluLookAt (0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
square();
glFlush();
}

void reshape (int w, int h) {
glViewport (0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective (60, (GLfloat)w / (GLfloat)h, 1.0, 100.0);
glMatrixMode (GL_MODELVIEW);
}

int main (int argc, char **argv) {
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_SINGLE);
glutInitWindowSize (500, 500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("A basic OpenGL Window");
glutDisplayFunc (display);
glutReshapeFunc (reshape);
glutMainLoop ();
return 0;
}

Download C++ Source Code for this Tutorial

Download Visual Basic Source Code for this Tutorial

     

 

Copyright 2008, Donald Urquhart
Proudly supported by http://www.cdadc.com