[英]Drawing a polygon when the mouse is clicked
考慮這段代碼:
#include <stdlib.h>
#include <stdarg.h>
#include <GLUT/GLUT.h>
#include <OpenGL/OpenGL.h>
double width=600;
double height=600;
void processMouse(int button, int state, int x, int y)
{
glColor4f(1.0,0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glFlush();
}
static void render()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
glutMouseFunc(processMouse);
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(width, height);
glutCreateWindow("Board");
glutDisplayFunc(render);
glutMainLoop();
}
render function 被執行,每執行一次點擊,它應該啟動 function processMouse。 因此,如果單擊鼠標,所有 window 都應變為紅色,並顯示以下說明:
glColor4f(1.0,0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glFlush();
但是當我單擊鼠標時,我注意到一個奇怪的行為:只有 window 的一部分變色,左下角的部分(而不是整個屏幕)。 window 保留在這個 state 中,直到我打開谷歌瀏覽器 window。如果我打開谷歌瀏覽器(或其他圖形應用程序),所有 window 都會變成紅色。 為什么這個? 我也遇到了更復雜的程序的問題,似乎有時會忽略 glVertex 指令。如果我嘗試使用 fprintf 調試程序,似乎一切正常,並且一切似乎都像預期的那樣 go(例如,我嘗試打印鼠標坐標在 processMouse function 中,它們沒問題),除了我繪制的內容被忽略了。
編輯:我已經修改了這段代碼,但它仍然有同樣的問題:
#include <stdlib.h>
#include <stdarg.h>
#include <GLUT/GLUT.h>
#include <OpenGL/OpenGL.h>
double width=600;
double height=600;
bool down=false;;
// http://elleestcrimi.me/2010/10/06/mouseevents-opengl/
static void render()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
if(down)
{
glColor4f(1.0,0.0,0.0,0.0);
glBegin(GL_POLYGON);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glVertex3f(1.0, 1.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glEnd();
glFlush();
}
}
void processMouse(int button, int state, int x, int y)
{
if(state==GLUT_DOWN)
{
down=true;
glutPostRedisplay();
}
}
int main(int argc, char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(width, height);
glutCreateWindow("Board");
glutMouseFunc(processMouse);
glutDisplayFunc(render);
glutMainLoop();
}
仍然只有一部分屏幕變紅。
PS:使用 glutSwapBuffers() 解決了,謝謝。
當你對 GLUT 使用雙緩沖時,你需要調用glutSwapBuffers()
來查看繪制的結果。
將其添加到您的render()
function 的末尾,它將正常工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.