Background colour in opengl

68,752

glClearColor does not do any clearing itself -- it just sets what the color will be when you do actually clear. To do the clearing itself, you need to call glClear with (at least) COLOR_BUFFER_BIT.

Edit: it's been quite a while since I used glut, so the details of this could be wrong, but if memory serves, to change the screen color in response to pressing a key on the keyboard, you'd do something like this:

void keyboard (unsigned char key, int x, int y)
{
    // we'll switch between red and blue when the user presses a key:
    GLfloat colors[][3] = { { 0.0f, 0.0f, 1.0f}, {1.0f, 0.0f, 0.0f } };
    static int back;

    switch (key) {
    case 27: 
        exit(0);
    default:
        back ^= 1;
        glClearColor(colors[back][0], colors[back][1], colors[back][2], 1.0f);
        glutPostRedisplay();
    }
}

void draw() { 
    glClear(GL_COLOR_BUFFER_BIT);
    // other drawing here...
}

int main() { 

    // glutInit, glutInitDisplayMode, etc.

     glutDisplayFunc(draw);
     glutKeyboardFunc(keyboard);
     glutMainLoop();
}

Basically, you do all your drawing in whatever function you pass to glutDisplayFunc. Almost anything else just changes the state, then calls PostRedisplayFunc(); to tell glut that the window needs to be redrawn. Warning: as I said, it's been a while since I used glut and I haven't tested this code. It shows the general structure of a glut program to the best of my recollection, but don't expect it to work exactly as-is.

Share:
68,752
lego69
Author by

lego69

Updated on January 29, 2021

Comments

  • lego69
    lego69 over 3 years

    I want to change the background color of the window after pressing the button, but my program doesn't work, can somebody tell me why?

    int main(int argc, char* argv[])
    {
      glutInit(&argc, argv);
      glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
      glutInitWindowSize(800, 600);
      glutInitWindowPosition(300,50);
      glutCreateWindow("GLRect");
            
      glClearColor(1.0f, 0.0f, 0.0f, 1.0f);   <---
        
      glutDisplayFunc(RenderScene);
      glutReshapeFunc(ChangeSize);
      glutMainLoop();
        
      system("pause");
      glClearColor(0.0f, 1.0f, 0.0f, 1.0f);   <---
        
      return 0;
    }
    
    • tafa
      tafa almost 14 years
      After pressing "what button"?
    • Troubadour
      Troubadour almost 14 years
      Since glutMainLoop() will never return how do you expect to get to your system("pause") statement and the second glClearColor call?
    • lego69
      lego69 almost 14 years
      @tafa: how can I change my code to see this effect?
  • lego69
    lego69 almost 14 years
    sorry, but I didn't understand, I'm beginner
  • lego69
    lego69 almost 14 years
    I did it,but it still doesn't work, may be problem with glutMainLoop?
  • Laz
    Laz almost 14 years
    This solution is fine. Try using double buffer? glutMainLoop is fine. Tell me if it works with double buffering