PROGRAM 7 SQUARE E. Angel
程式敘述 建立一個以黑色為背景顏色的視窗 當滑鼠游標在視窗內按住左鍵移動,在視窗上便會留下以固定大小而顏色不斷改變的方塊所形成之軌跡
#include <GL/glut.h> #include <stdlib.h> GLsizei wh = 500, ww = 500; GLfloat size = 3.0; void drawSquare(int x, int y) { y=wh-y; glColor3ub( (char) rand()%256, (char) rand()%256, (char) rand()%256); glBegin(GL_POLYGON); glVertex2f(x+size, y+size); glVertex2f(x-size, y+size); glVertex2f(x-size, y-size); glVertex2f(x+size, y-size); glEnd(); glFlush(); }
void myinit(void) { glViewport(0,0,ww,wh); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0, (GLdouble) ww , 0.0, (GLdouble) wh , -1.0, 1.0); glClearColor (0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); glFlush(); glutReshapeFunc(myReshape); }
void mouse(int btn, int state, int x, int y) { if(btn==GLUT_RIGHT_BUTTON && state==GLUT_DOWN) exit(0); } void display(void) {} int main(int argc, char** argv) glutInit(&argc,argv); glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB); glutCreateWindow("square"); myinit (); glutReshapeFunc (myReshape); glutMouseFunc (mouse); glutMotionFunc(drawSquare);//當按住滑鼠按鍵在視窗內移動,於是此函式便會呼叫drawSquare這個函式 glutDisplayFunc(display); glutMainLoop();
執行結果