//程序如下:
GLsizei winwidth = 500;
GLsizei winHeight = 500;
GLint endPtctr = 0;
class scrPt
{
public:
GLint x,y;
};
void init()
{
glClearColor(0.0,0.0,0.0,1.0);
glMatrixMode(GL_PROJECTION);
gluOrtho2D(0.0,300.0,0.0,300.0);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
}
void reshape(int w,int h)
{
glViewport(0,0,(GLsizei)w,(GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0,(GLdouble)w,0.0,(GLdouble)h);
winwidth = w;
winHeight = h;
}
void plotpoint(GLint x,GLint y)
{
glPointSize(5);
glBegin(GL_POINTS);
glVertex2i(x,y);
//glVertex2i(endpt2.x,endpt2.y);
glEnd();
}
void draw_line(scrPt endpt1,scrPt endpt2)
{
//glFlush();
glLineWidth(5);
glColor3f(1.0,0.0,0.0);
glBegin(GL_LINES);
glVertex2i(endpt1.x,endpt1.y);
glVertex2i(endpt2.x,endpt2.y);
glEnd();
}
void polyline(GLint button,GLint action,GLint xMouse, GLint yMouse)
{
static scrPt endpt1,endPt2;
if(endPtctr == 0)
{
if (button == GLUT_LEFT_BUTTON && action ==GLUT_DOWN)
{
endpt1.x = xMouse;
endpt1.y = winHeight - yMouse;
plotpoint(xMouse,winHeight-yMouse);
endPtctr = 1;
}
else
{
if (button == GLUT_RIGHT_BUTTON)//quit the program
{
exit(0);
}
}
}
else
{
if (button == GLUT_LEFT_BUTTON && action == GLUT_DOWN)
{
endPt2.x = xMouse;
endPt2.y = winHeight - yMouse;
draw_line(endpt1,endPt2);
endpt1 = endPt2;
}
else
{
if (button == GLUT_RIGHT_BUTTON)
{
exit(0);
}
}
}
glFlush();
}
int main(int argc,char **argv)
{
glutInit(&argc,argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(winwidth,winHeight);
glutInitWindowPosition(200,200);
glutCreateWindow("hello");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMouseFunc(polyline);
glutMainLoop();
return 0;
}