| |
How to assign colour values to Vertices with OpenGL
Back to OpenGL Tutorial Index
This OpenGL tutorial will show you how to add colors to specific vertices in your shape. It uses the same color commands but the code is now written just before each vertex.
Vertex coloring is nothing really special
it is just normal coloring, only setting the colors
to specific vertices instead of whole objects.
This then blends the colors into each other
forming a nice little rainbow type thing
with the colors I have chosen.
So anyway, I did this with a normal quad
but it does work with any shape you choose
Here it is:
I have started my quad.
I then set the color red for the first vertex.
I then draw that vertex.
The next is green.
Then blue.
And finally white.
glBegin(GL_QUADS);
glColor3f(1,0,0);
glVertex3f(-0.5, -0.5, 0.0);
glColor3f(0,1,0);
glVertex3f(-0.5, 0.5, 0.0);
glColor3f(0,0,1);
glVertex3f(0.5, 0.5, 0.0);
glColor3f(1,1,1);
glVertex3f(0.5, -0.5, 0.0);
glEnd();
Just remember to call each vertex after you call the color
for this to work.
#include <GL/gl.h>
#include <GL/glut.h>
void square (void) {
glBegin(GL_QUADS);
glColor3f(1,0,0); //red
glVertex3f(-0.5, -0.5, 0.0);
glColor3f(0,1,0); //green
glVertex3f(-0.5, 0.5, 0.0);
glColor3f(0,0,1); //blue
glVertex3f(0.5, 0.5, 0.0);
glColor3f(1,1,1); //white
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();
glTranslatef(0,0,-1);
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 |
 |