I'm trying to draw multiple rectangles in this program, but whenever I draw a new rectangle, the old rectangle disappears, how can I draw a new rectangle without losing the old rectangle? This is my program:
struct Position
{
Position() : x(0), y(0) {}
float x, y;
};
Position start, finish;
void mouse(int button, int state, int x, int y)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN)
{
start.x = finish.x = x;
start.y = finish.y = y;
}
if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
{
finish.x = x;
finish.y = y;
}
glutPostRedisplay();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_QUADS);
glVertex2f(start.x, start.y);
glVertex2f(finish.x, start.y);
glVertex2f(finish.x, finish.y);
glVertex2f(start.x, finish.y);
glEnd();
glFlush();
}
Note that simply removing glClear
would lead to all rectangles you ever drawn persisting on the screen - you won't be able to e.g. delete just one of them. It may also lead to the initial contents of the window contain some garbage pixels (though this can be fixed by doing glClear
just at the start of your program).
A typical solution would be, as jackw11111 suggested, to store all your rectangle coordinates in some data structure (std::vector
being a perfect choice if you're on C++), and in your display
function you'd first do the glClear
, and then iterate over all rectangles and draw them one by one. Something like
struct Rectangle
{
Position start, finish;
};
std::vector<Rectangle> rectangles;
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_QUADS);
for (Rectangle const & r : rectangles)
{
glVertex2f(r.start.x, r.start.y);
glVertex2f(r.finish.x, r.start.y);
glVertex2f(r.finish.x, r.finish.y);
glVertex2f(r.start.x, r.finish.y);
}
glEnd();
}
By the way, you almost definitely don't need glFlush
.