Background Color change of window is removing all drawings

I am pretty new to openGL and I want to draw an animation in openGL.
For this I changed the openGL background using the code:
glClearColor(0.3f, 0.4f, 0.1f,1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

but the problem is this is clearing my whole window including the images I have drawn on this.
I just want to change the background color without clearing my drawings.

I am using openGL 2.1 with glfw.

THANKS

glClear doesn’t really set a background color, it sets all values on the screen to the color you specified in glClearColor (and depths to glClearDepth… leave it at 1). Think of it glClearColor as changing the backing color of a dry-erase board and glClear as erasing the dry-erase board.

You should call this at the start of your frame, so before you draw everything else. If you are expecting to fill the screen with drawing (e.g. drawing a tiled 2D map) you can skip this.

If you are just drawing 2D images, you can skip using the Z-buffer (depth buffer) for a slight performance improvement:


glDisable( GL_DEPTH_TEST ); // here for illustrative purposes, depth test is initially DISABLED (key!)
glClearColor(0.3f, 0.4f, 0.1f,1.0f);
glClear(GL_COLOR_BUFFER_BIT);

… I want to draw an animation …
… the problem is this is clearing my whole window including the images I have drawn on this.
I just want to change the background color without clearing my drawings.

Animation is usually done in GL by redrawing the entire scene for each frame.
This starts with clearing the screen to the background color, then redrawing all of the
elements in the scene including the ones that don’t move, change appearance, etc.
Since you are doing ‘animation’, I assume something is moving in the scene. Try this - don’t
call glClear, and run your animation. See what the problem is? Without glClear, you’d have
to figure out what pixels to erase (i.e. replace with the background color) on each frame. It’s
too messy. GL is fast enough to redraw everything in the scene each frame.

Am I interpreting your issue correctly?