OpenGL不显示2D线

时间:2018-09-12 15:14:11

标签: c++ linux opengl glut

我正在使用Ubuntu 18.04 LTS,并尝试使用OpenGl实现2D行,但未显示任何内容。我正在使用ubuntu编译器。我已经使用终端安装了该库。

这是我的代码

#include <GL/glut.h>
void display()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glBegin(GL_LINES);
    glVertex2i(10,10);
    glVertex2i(100,100);
    glEnd();

    glFlush();
}

int main(int argc, char** argv)
{
    glutInit(&argc,argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize (500, 500);
    glutInitWindowPosition (100, 100);
    glutCreateWindow ("points and lines");
    glutDisplayFunc(display);
    glutMainLoop();

    return 0;
}

这就是我编译和运行程序的方式

 g++ jamshaid.cpp -o jamoo -lglut -lGLU -lGL
./jamoo

更新1

添加了init2D并尝试了其他答案,但是没有用。它甚至都不会更改窗口的标题。

更新2

this网站更新代码后。我现在有了这段代码,它正在工作。请您解释一下原因。谢谢

#include <GL/glut.h>

 void init2D(float r, float g, float b)
 {
 glClearColor(r,g,b,0.0);  
 glMatrixMode (GL_PROJECTION);
gluOrtho2D (0.0, 200.0, 0.0, 150.0);
}

void display(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINES);
    glVertex2i(10,10);
    glVertex2i(100,100);
 glEnd();
 glFlush();
 }

int main(int argc,char *argv[])
 {
 glutInit(&argc,argv);
 glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
 glutInitWindowSize (500, 500);
 glutInitWindowPosition (100, 100);
 glutCreateWindow ("points and lines");
 init2D(0.0,0.0,0.0);
 glutDisplayFunc(display);
 glutMainLoop();
 return 0;}

2 个答案:

答案 0 :(得分:1)

如示例here所示,您需要一个正确的init2D函数来在绘制之前初始化3D投影矩阵。

void init2D(float r, float g, float b)
{
    glClearColor(r,g,b,0.0);  
    glMatrixMode (GL_PROJECTION);
    gluOrtho2D (0.0, 200.0, 0.0, 150.0);
}

答案 1 :(得分:0)

Tung Le Thanh告诉您,您需要正确的投影矩阵初始化,这就是它的作用:

glMatrixMode (GL_PROJECTION)

  

glMatrixMode-指定哪个矩阵为当前矩阵

                GL_PROJECTION
                    Applies subsequent matrix operations to the projection matrix stack.
                GL_TEXTURE
                    Applies subsequent matrix operations to the texture matrix stack.
                GL_COLOR
                    Applies subsequent matrix operations to the color matrix stack.

        To find out which matrix stack is currently the target of all matrix
        operations, call glGet with argument GL_MATRIX_MODE. The initial
        value is GL_MODELVIEW.

gluOrtho2D

  

gluOrtho2D-定义2D正交投影矩阵

     

规格

void gluOrtho2D(GLdouble left,  GLdouble right,  GLdouble bottom,  GLdouble top); 
     

参数

  left, right
            Specify the coordinates for the left and right vertical clipping planes.
  bottom, top
            Specify the coordinates for the bottom and top horizontal clipping planes.
     

说明

        gluOrtho2D sets up a two-dimensional orthographic viewing region.