#include
#include
#include
#define DEG_TO_RAD 0.017453 //角度转为弧度的参数,即 2*PI/360
GLboolean rotate = GL_TRUE;
float theta=30.0; //直线与X轴正方向的夹角
float length=200.0; //直线的长度
float x=300.0, y=200.0; //直线的第一个端点
void init (void)
{
glClearColor (1.0, 1.0, 1.0, 0.0);
glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 640.0, 0.0, 480.0);
}
void display (void)
{
glClear (GL_COLOR_BUFFER_BIT);
glColor3f (1.0, 0.0, 0.0);
glBegin (GL_POLYGON);
glVertex2f (x, y);
glVertex2f ( x + length*cos(DEG_TO_RAD*theta),
y + length*sin(DEG_TO_RAD*theta) );
glVertex2f ( x + length*cos(DEG_TO_RAD* (theta+30) ),
y + length*sin(DEG_TO_RAD* (theta+30)) );
glEnd ( );
glutSwapBuffers ( ); //交换前后台缓存
}
void myKeyboard(unsigned char key, int x, int y)
{
if(key == 'a' || key == 'A')
theta += 5.0;
if(key == 's' || key == 'S')
theta -= 5.0;
if(key == 'c' || key == 'C')
exit(0);
if (theta>360) theta -=360;
if (theta<0) theta +=360;
glutPostRedisplay(); //重新调用绘制函数
}
void main (int argc, char** argv)
{
glutInit (&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB);
glutInitWindowPosition (100, 100);
glutInitWindowSize (640, 480);
glutCreateWindow("Draw Triangle with Double Buffer");
init();
glutDisplayFunc (display);
glutKeyboardFunc( myKeyboard);
glutMainLoop ( );
}通过键盘控制曲线的粗细
#include
#include
#define PI 3.14
GLint size = 1;
void drawMyLines()
{
float t;
float x,y,z;
float a=2,b=3,c=18;
glColor3f(1.0,0.5,0.5);
glLineWidth(size);
glBegin(GL_LINE_STRIP);
for(t=0.0;t<=2*PI;t+=0.0002)
{
x=a*t*cos(c*t)+b;
y=a*t*sin(c*t)+b;
z=c*t;
glVertex3f(x,y,z);
}
glEnd();
glLineWidth(1);
glColor3f(1.0,1.0,1.0);
glBegin(GL_LINES); //建立坐标轴
glVertex3f(0,0,0);
glVertex3f(12,0,0);
glEnd();
glBegin(GL_LINES); //建立坐标轴
glVertex3f(0,0,0);
glVertex3f(0,0,12);
glEnd();
glBegin(GL_LINES); //建立坐标轴
glVertex3f(0,0,0);
glVertex3f(0,12,0);
glEnd();
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
drawMyLines(); //调用drawMyLines函数
glFlush();
}
void myKeyboard(unsigned char key,int x,int y)
{
switch(key)
{
case '1':
size++;
break;
case '2':
size--;
break;
}
glutPostRedisplay();
}
void init()
{
glClearColor(0.0,0.0,0.0,0.0);
glColor3f(1.0,1.0,1.0);
gluLookAt(1,1,1, //更改视角
3,3,3,
-1,-1,1
);
glMatrixMode(GL_PROJECTION); //设置投影模式
glLoadIdentity(); //设置单位矩形
glOrtho(-12.0,12.0,-12.0,12.0,-12,12);
}
int main(int argc, char* argv[])
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(500, 500);
glutInitWindowPosition(0, 0);
glutCreateWindow("Simple");
glutDisplayFunc(display);
init();
glutKeyboardFunc(myKeyboard);
glutMainLoop(); //使程序一直处在监听状态中
return 0;
}