How to clear the screen in openGL

I am new to openGL
I have written the code to display a polygon on the window
after that i have tried to clear the screen using glClearColor and glClear functions
The code i have written is


#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
void display(void)
{
	int i;
	
	glClear(GL_COLOR_BUFFER_BIT);
	glColor3f(0.0, 0.0, 1.0);
	
	glBegin(GL_POLYGON);
	glVertex3f(1.1, 1.1, 0.1);
	glVertex3f(2.7, 2.1, 0.5);
	glVertex3f(2.7, 2.7, 0.1);
	glVertex3f(1.1, 2.7, 0.5);
	glEnd();

	glFlush();
}
void init(void)
{
	glClearColor(1.0,0.0,0.0,0.0);
	

	//glMatrixMode(GL_PROJECTION);
	//glLoadIdentity();
	glOrtho(0.0, 3.0, 0.0, 3.0, -1.0, 1.0);

}

int main(int argc,char **argv)
{
	glutInit(&argc,argv);
	glutInitDisplayMode(GLUT_DEPTH | GLUT_RGB | GLUT_SINGLE);
	//glutInitWindowSize(1600, 1600);
	//glutInitWindowPosition(100, 100);
        

	glutCreateWindow("hello");
	glClearColor(1.0f,0.0f,0.0f,0.0f);
	glClear(GL_COLOR_BUFFER_BIT);
	init();
	glutDisplayFunc(display);
	glClearColor(0.0,1.0,0.0,0.0);
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	//glutReshapeFunc(resize(100,200));
	glutMainLoop();
	return 0;
}

I am able to change the background color but i am unable to remove the polygon which i drew.

please help

Thanks in advance

gl_siddarth

Just reverse these two statements in your main()after you call display()

glClearColor(0.0,1.0,0.0,0.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

I have tried swapping those two methods “awhig” but no luck,
i did not understand the purpose of swapping them,

please tell me

I missed a line while going through your code. Disregard my previous post.

You need to clear your buffer before flush() in display().
In your display() , after you create your polygon you flush() it to render.

After your glutDisplayFunc(display); is called in main(), the buffer is empty. At next statement you are again clearing your buffer with green color. This green colored buffer is used for your next iteration where again your blue colored object is drawn.

Thus, your object is drawn on top every time.

As stated, I suggested you above as I mis-read your polygon color to be green (0,1,0) instead of (0,0,1). My idea was to just repaint everything using the same color.

how can i prevent the object being drawn every-time, i want the complete screen to be cleared with the color i have set in glClearColor function

please help me

In that case, you can create a display list for your object and call it on condition.

Condition may be set using your keyboard. i.e if you press particular key the list is called.

You need to put in some small functions in side display() to achieve above.

Create your display list in init().