I am trying to draw lines in opengl using mouse clicks, but everytime I click a line between coordinates (0, 0) (corner left) and the actual mouse click is drawn. I want to have only the lines drawn in between clicks. Here is the mouse function:
int i = 0, x[50], y[50];
void mouse(int button, int state, int mousex, int mousey)
{
if (button == GLUT_LEFT_BUTTON && state == GLUT_UP)
{
x[i] = mousex;
y[i] = 480 - mousey;
i++;
}
else if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)//undo(clear)the drawing
{
glClearColor(1, 1, 1, 0);
glClear(GL_COLOR_BUFFER_BIT);
}
glutPostRedisplay();
}
Below I have the display function where I draw the actual lines and the main function:
void display(void)
{
glColor3f(1, 0, 1);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, 640.0, 0.0, 480.0);
for (int k = 0; k <= i; k++)
{
glBegin(GL_LINES);
glVertex2f(x[k], y[k]);
glVertex2f(x[k + 1], y[k + 1]);
glEnd();
}
glFlush(); // flushes the frame buffer to the screen
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitWindowSize(640, 480);
glutInitWindowPosition(10, 10);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutCreateWindow("Line Drawing");
glClearColor(1, 1, 1, 0);
glClear(GL_COLOR_BUFFER_BIT);
glutDisplayFunc(display);
glutMouseFunc(mouse);
glutMainLoop();
}
This is what it draws when I click 3 times for example:
question from:
https://stackoverflow.com/questions/65888032/draw-lines-using-mouse-clicks-opengl 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…