Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

c++ - Draw lines using mouse clicks OPENGL

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: EXAMPLE

question from:https://stackoverflow.com/questions/65888032/draw-lines-using-mouse-clicks-opengl

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change this

for (int k = 0; k <= i; k++) // CAREFUL -- there are i points
{
    glBegin(GL_LINES);
        glVertex2f(x[k], y[k]);
        glVertex2f(x[k + 1], y[k + 1]);  // CAREFUL k+1 = i+1 in last iteration
    glEnd();

}

to this

glBegin(GL_LINE_STRIP);
for (int k = 0; k < i; k++) 
{                           
        glVertex2f(x[k], y[k]);
}
glEnd();

The reason you are getting the extra lines back to (0,0) is that you are referencing the ith and (i+1)th elements in the buffer which are beyond the end of your recorded points and are statically initialized to zero.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...