功能:鼠标左击个对焦点画出矩形,鼠标右键清除画布。
就这么简单的鼠标交互,鼠标右键清除缓存的时候,用glFLush()就是实现不了,调试发现就是堵在了if (button == GLUT_RIGHT_BUTTON){}里面。明明是照着书敲的代码,甚至朋友copy我的代码装了环境在他的电脑上跑程序,glFlush()都没问题。云调试到凌晨1点得出结论–我的电脑只能glClearColor(1.0, 1.0, 1.0, 0.0); glClear(GL_COLOR_BUFFER_BIT);glFinish();这样搭配着用
代码如下:
#include <gl/glut.h>
#include<gl/GLU.h>
#include<Windows.h>
#include<math.h>
#include<iostream>
using namespace std;
//鼠标互动
struct GLPoint {
GLint x;
GLint y;
};
//起始点
GLPoint window_point = { 0,0 };
//函数重载
void drawPoint(GLint x,GLint y) {
glBegin(GL_POINTS);
glVertex2i(x, y);
glEnd();
}
void drawPoint(GLfloat x, GLfloat y) {
glBegin(GL_POINTS);
glVertex2f(x, y);
glEnd();
}
//定义窗口大小
GLint wide = 640;
GLint height = 640;
//还是写一个画点函数吧,因为需要将glBegin()glEnd()配套用
void myInit(void) {
//设置画布背景颜色--白色,RGB和透明度alpha
glClearColor(1.0, 1.0, 1.0,0.0);
//设置画图的颜色 这里只有一种颜色--黑色
glColor3f(0.0f, 0.0f, 0.0f);
//设置点的大小为10*10像素大小,所绘点过多,像素调至2
glPointSize(10.0);
glLineWidth(4.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, wide*1.0, 0.0, height*1.0);
}
void myDisplay(void) {
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void myMouse(int button, int state, int x, int y) {
//点击鼠标
static GLPoint rec_points[2];
static GLint num_point = 0;
if (state == GLUT_DOWN) {
if(button == GLUT_LEFT_BUTTON){
rec_points[num_point].x = x;
rec_points[num_point].y = y;
cout << 000 << endl;
num_point++;
if (num_point >= 2) {
glRecti(rec_points[0].x, height-rec_points[0].y, rec_points[1].x, height - rec_points[1].y);
glFlush();
num_point = 0;
}
}
else if (button == GLUT_RIGHT_BUTTON) {
glClearColor(1.0, 1.0, 1.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT);
glFinish();
}
}
}
int main(int argc, char* argv[])
{
//初始化工具包
glutInit(&argc, argv);
//设置显示模式
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
//设置窗口大小
glutInitWindowSize(wide, height);
//设置窗口位置
glutInitWindowPosition(100, 150);
glutCreateWindow("Kate's test");
//注册回调函数
glutDisplayFunc(myDisplay);
glutMouseFunc(myMouse);
myInit();
glutMainLoop();
return 0;
}