OpenGL使用笔记【2】鼠标交互操作

这个有点难度了。

glutMouseFunc()函数

这个函数就是关于鼠标点击的调用函数。
用法:
添加在main函数中
顺便再搞一个函数作为鼠标事件判定函数

int main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GL_DOUBLE | GLUT_RGB);
	glutInitWindowSize(800, 600);
	glutCreateWindow("画图");//创建窗口,设置窗口名称
	
	Reshape(800, 600);//初始化
	glutDisplayFunc(drawlines);//绘制
	glutMouseFunc(mymouse);
	glutMainLoop();
	return 0;
}

例如:

struct POINT
{
	int x;
	int y;
};
POINT a = { 10,10 };
void mymouse(int button, int state, int x, int y) {
	if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON)
	{
		
		a = { x,hh-y };
		glutPostRedisplay();
		//这个函数功能是.当你的回调函数处理完键盘事件后,显示函数会自动被调用,屏幕会被重绘。也就是保证了鼠标点击可以重复执行之类的
	}
}
//GLUT_LEFT_BUTTON表示鼠标左键
//GLUT_DOWN表示鼠标右键

以上mymouse函数的意思也就是鼠标左键单击后设置点的坐标
绘画逻辑:

void drawlines() {
	GLfloat r=0, g=0, b=0;
	glClear(GL_COLOR_BUFFER_BIT);
	glPointSize(3);//设置点的大小
	glBegin(GL_POINTS);
	glColor3f(0, 0, 0);
	glVertex2i(a.x, a.y); 
	glEnd();
	glutSwapBuffers();//缓冲刷新
	}

连起来:

#include <GL/glut.h>
//按照环境配置教程里面的话就应该
struct POINT
{
	int x;
	int y;
};
int ww, hh;
POINT a = { 10,10 };
void mymouse(int button, int state, int x, int y) {
	if (state == GLUT_DOWN && button == GLUT_LEFT_BUTTON)
	{
		
		a = { x,hh-y };
		glutPostRedisplay();
		//这个函数功能是.当你的回调函数处理完键盘事件后,显示函数会自动被调用,屏幕会被重绘。也就是保证了鼠标点击可以重复执行之类的
	}
}
//GLUT_LEFT_BUTTON表示鼠标左键
//GLUT_DOWN表示鼠标右键
//窗口属性,每次刷新基于这个属性
void Reshape(int w, int h) {
	glMatrixMode(GL_PROJECTION);//设置投影方式,有用的,目前来说不必深究
	glClearColor(255, 255, 255, 0);
	glLoadIdentity();
	gluOrtho2D(0, w, 0, h);        // 设置裁剪窗口大小
	ww = w;
	hh = h;
}

void drawlines() {
	glClear(GL_COLOR_BUFFER_BIT);
	glPointSize(3);//设置点的大小
	glBegin(GL_POINTS);
	glColor3f(0, 0, 0);
	glVertex2i(a.x, a.y);
	glEnd();
	glutSwapBuffers();
}

int main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GL_DOUBLE | GLUT_RGB);
	glutInitWindowSize(800, 600);
	glutCreateWindow("画图");//创建窗口,设置窗口名称
	
	Reshape(800, 600);//初始化
	glutDisplayFunc(drawlines);//绘制
	glutMouseFunc(mymouse);
	glutMainLoop();
	return 0;
}

请添加图片描述