【发布时间】:2019-11-06 23:43:14
【问题描述】:
所以我试图在 OpenGL 中在我单击的点之间画线。如果我按下左键,绘图会在屏幕上显示,但如果我松开左键,它就会消失:
struct Vector {
float x, y;
Vector(float x = 0, float y = 0) : x(x), y(y) {}
} last_mouse_pos;
void onInitialization() {
glClearColor(0, 0, 0, 0); // A hatterszin beallitasa.
glClear(GL_COLOR_BUFFER_BIT); // A kepernyo torlese, az uj hatterszinnel.
}
void onDisplay() {
glutSwapBuffers();
}
Vector convertToNdc(float x, float y) {
Vector ret;
ret.x = (x - kScreenWidth / 2) / (kScreenWidth / 2);
ret.y = (kScreenHeight / 2 - y) / (kScreenHeight / 2);
return ret;
}
int i = 0;
void onMouse(int button, int state, int x, int y) {
if (button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
glClear(GL_COLOR_BUFFER_BIT);
glutPostRedisplay();
}
else if (button == GLUT_LEFT_BUTTON) {
if (state == GLUT_DOWN) {
i++;
if (i == 1) last_mouse_pos = convertToNdc(x, y);
if (i > 1) {
Vector pos = convertToNdc(x, y);
glBegin(GL_LINES);
glVertex2f(last_mouse_pos.x, last_mouse_pos.y);
glVertex2f(pos.x, pos.y);
glEnd();
glutPostRedisplay();
last_mouse_pos = pos;
}
}
}
}
所以我做了2点,如果我按住左键,它会画线,如果我松开它,屏幕会变黑。如果我点击其他地方,现在我有 2 行,但前提是我按下左键。如果我释放,它会再次变黑。
【问题讨论】:
-
您可能收到了
WM_ERASE消息。 -
您的绘图仅发生在鼠标按下代码中。OpenGL 中的缓冲区被交换(在您的情况下:
glutSwapBuffers).. 您没有绘制每一帧,因此在下一帧时它会被擦除呈现。 -
如果我已经换了...为什么又换回来了?
-
不要在你的输入回调中绘制,锁定一些状态并通过
glutPostRedisplay()请求重新调用你的显示回调并在那里绘制。