opengl 绘制3D 坐标 图表 代码
时间: 2023-08-24 09:03:57 浏览: 160
下面是一个使用OpenGL绘制三维散点图的示例代码,其中包括了上述步骤的实现。
```c++
#include <GL/glut.h>
#include <math.h>
typedef struct {
float x, y, z;
float r, g, b;
} Point3D;
Point3D points[] = {
{0.5, 0.5, 0.5, 1.0, 0.0, 0.0},
{0.5, -0.5, 0.5, 1.0, 1.0, 0.0},
{-0.5, -0.5, 0.5, 0.0, 1.0, 0.0},
{-0.5, 0.5, 0.5, 0.0, 0.0, 1.0},
{0.5, 0.5, -0.5, 1.0, 0.0, 1.0},
{0.5, -0.5, -0.5, 1.0, 1.0, 1.0},
{-0.5, -0.5, -0.5, 0.0, 1.0, 1.0},
{-0.5, 0.5, -0.5, 0.5, 0.5, 0.5}
};
void init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_SMOOTH);
}
void display(void)
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// 绘制坐标轴
glBegin(GL_LINES);
glColor3f(1.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(1.0, 0.0, 0.0);
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 1.0, 0.0);
glColor3f(0.0, 0.0, 1.0);
glVertex3f(0.0, 0.0, 0.0);
glVertex3f(0.0, 0.0, 1.0);
glEnd();
// 绘制散点
glPointSize(5.0);
glBegin(GL_POINTS);
for (int i = 0; i < sizeof(points) / sizeof(points[0]); i++) {
glColor3f(points[i].r, points[i].g, points[i].b);
glVertex3f(points[i].x, points[i].y, points[i].z);
}
glEnd();
glFlush();
}
void reshape(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(60.0, (GLfloat)w / (GLfloat)h, 0.1, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(0.0, 0.0, 5.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
}
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(500, 500);
glutInitWindowPosition(100, 100);
glutCreateWindow("3D Scatter Plot");
init();
glutDisplayFunc(display);
glutReshapeFunc(reshape);
glutMainLoop();
return 0;
}
```
注意:需要链接OpenGL和glut库才能编译通过。
阅读全文