View Full Version : newbie open gl color syntax

02-28-2005, 05:28 AM
hi, I'm quite new to opengl and have run into a problem, I am trying to change the background color on the window via keyboard input as u can see from the code below. the code builds and compiles with no errors but when I press 'r' to change the background colour to red nothing happens.... can someone help please

thanks in advance much appreciated

#include <windows.h>
#include <gl/Gl.h>
#include <gl/Glu.h>
#include <gl/glut.h>
#include <stdio.h>

void myDisplay(void){

glClearColor(0.0, 0.0, 0.0, 0.0); // paint the window background with black
glClear(GL_COLOR_BUFFER_BIT); // clear screen with the above colour
glVertex2f(-0.5, -0.5); // draw three points
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glFlush(); // send all output to display


void myKeyboard ( unsigned char key, int x, int y ) // Create Keyboard Function
switch (key) {
case 'r': // When r is pressed change to red
glColor3f(1.0, 0.0, 0.0);
break; // Ready For Next Case

void main(int argc, char** argv)

glutInit(&argc, argv); // initialize the GLUT toolkit
glutInitDisplayMode(GLUT_RGB |GLUT_SINGLE); // set display mode
glutInitWindowSize(640,480); // set window size
glutInitWindowPosition(100, 150); // set window position on screen
glutCreateWindow("My First OpenGL program"); // open the screen window
glutDisplayFunc(myDisplay); // register draw function
glutMainLoop(); // go into a perpetual loop


02-28-2005, 05:43 AM
First of all, you have to set the keyboard function before calling glutMainLoop(). glutMainLoop doesn't return, so there shouldn't be anything after it in the main() function.

The background color is set using glClearColor, you call glColor. Move the glClearColor call out of the display function into the main function somewhere after glutCreateWindow (it is good style to write an init() function that does this sort of things, and call it from main).

Then change the glColor call in the keyboard function to glClearColor. You also have to call glutPostRedisplay() after changing the background color to force a redraw of the scene.