使用鼠标点击 OPENGL 绘制线条

Draw lines using mouse clicks OPENGL

我正在尝试使用鼠标点击在 opengl 中绘制线条,但每次我点击坐标 (0, 0)(左角)之间的线条时,都会绘制实际的鼠标点击。我只想在点击之间绘制线条。这是鼠标功能:

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();
}

下面是绘制实际线条的显示函数和主要函数:

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();
}

这是我点击3次后的画面,例如:

改变这个

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();

}

至此

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

你将额外的行返回到 (0,0) 的原因是你引用了缓冲区中的第 i(i+1) 个元素,这些元素超出了你的末尾记录点并静态初始化为零。