Search code examples
c++openglglut

Why drawing a line in OpenGL is not working?


GLfloat vertices[NUM_VERTICES][3] = {
    
{ -0.5, -0.4, 0.0 },
    {  0.5, -0.4, 0.0 },
    {  0.5,  0.4, 0.0 },
    {  0.0,  0.8, 0.0 },
    { -0.5,  0.4, 0.0 }
};
void init() {
  glClearColor(0.0, 0.0, 0.0, 0.0);
  glShadeModel(GL_FLAT);
}

void display() {
  glClear(GL_COLOR_BUFFER_BIT);
  glBegin(GL_POLYGON);
  for (int i = 0; i < NUM_VERTICES; i++) {
    
    glColor3fv(colors[i]);
    glVertex3fv(vertices[i]);
    }
  glEnd();
  glutSwapBuffers();
  glClear(GL_COLOR_BUFFER_BIT);
  //glClearColor(0.0, 0.0, 0.0, 0.0);
  glShadeModel(GL_FLAT);
  glColor3ub(1.0, 1.0, 1.0);        
  glLineWidth(10);
  glBegin(GL_LINES);
  glVertex2f(0.0, -0.4); 
  glVertex2f(0.0, 0.8); 
  glEnd();
}

I drew a pentagon using OpenGL. I want to draw a line from one point to another inside the pentagon but it doesn't work. How to make it work?


Solution

  • glClear clears the entire framebuffer and must be called once before drawing all of the geometry. If you call it in between, all previous drawings will be cleared. glutSwapBuffers() swaps the buffers and updates the display and must be called after drawing all the objects in the scene:

    void display() {
      glClear(GL_COLOR_BUFFER_BIT);
    
      glBegin(GL_POLYGON);
      for (int i = 0; i < NUM_VERTICES; i++) {    
        glColor3fv(colors[i]);
        glVertex3fv(vertices[i]);
      }
      glEnd();
      
      glColor3ub(1.0, 1.0, 1.0);        
      glLineWidth(10);
      glBegin(GL_LINES);
      glVertex2f(0.0, -0.4); 
      glVertex2f(0.0, 0.8); 
      glEnd();
    
      glutSwapBuffers();
    }