pyopengl鼠标点击屏幕画点
参数解析:
- button,以下的参数分别可以用0,1,2表示
- GLUT_LEFT_BUTTON:鼠标左键
- GLUT_MIDDLE_BUTTON:鼠标中键
- GLUT_RIGHT_BUTTON:鼠标右键
- state,以下的参数分别可以用0,1表示
- GLUT_DOWN:鼠标按下
- GLUT_UP:鼠标松开
注意事项:
- glPointSize,设置画的点的大小,始终放在glBegin()前面
- gluOrtho2D将坐标转为世界坐标,不设置的时候坐标的范围为[-1,1],设置后可以得到屏幕上的坐标,范围为[0,width],[0,height]。如果设置为gluOrtho2D(0, width, height, 0),点击哪里就会将点显示在哪里,如果设置为gluOrtho2D(0, width, 0,height),将会反转,可以修改为这个测试一下效果。
from sys import argv
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *
class MyPyOpenGLTest:
def __init__(self, width=640, height=480, title="测试"):
self.button_kind = -1
self.hit_pos_x = None
self.hit_pos_y = None
self.move_pos_x = None
self.move_pos_y = None
self.width = width
self.height = height
glutInit(argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
glutInitWindowSize(width, height)
glutCreateWindow(title.encode('gbk'))
glMatrixMode(GL_MODELVIEW | GL_PROJECTION)
gluOrtho2D(0, width, height, 0)
glutDisplayFunc(self.display) # 显示函数
glutMouseFunc(self.myMouse) # 鼠标事件
glutMotionFunc(self.mouse_move)
glutMainLoop()
def display(self):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
if self.button_kind == 0:
glPointSize(5)
glBegin(GL_POINTS)
glColor3f(0, 0, 1) # 蓝色
glVertex2f(self.hit_pos_x, self.hit_pos_y)
print(self.hit_pos_x, self.hit_pos_y)
glEnd()
elif self.button_kind == 2:
glPointSize(20)
glBegin(GL_POINTS)
glColor3f(0, 1, 0) # 绿色
glVertex2f(self.hit_pos_x, self.hit_pos_y)
glEnd()
elif self.button_kind == 3:
glLineWidth(5)
glColor3f(1, 0, 0) # 红色
glBegin(GL_LINES)
glVertex2f(self.hit_pos_x, self.hit_pos_y)
glVertex2f(self.move_pos_x, self.move_pos_y)
glEnd()
glutSwapBuffers()
glutPostRedisplay()
def myMouse(self, button, state, x, y):
self.button_kind = button
if button == GLUT_LEFT_BUTTON:
if state == GLUT_DOWN:
self.hit_pos_x = x
self.hit_pos_y = y
elif button == GLUT_RIGHT_BUTTON:
if state == GLUT_DOWN:
self.hit_pos_x = x
self.hit_pos_y = y
def mouse_move(self, x, y):
self.button_kind = 3
self.move_pos_x = x
self.move_pos_y = y
if __name__ == "__main__":
a = MyPyOpenGLTest()