Search code examples
opengllineglut

OpenGL Line Drawing


I am practicing the exercises from my textbook but I could not get the outputs that I should.

Here is what I have :

#include <math.h>
#include <GLUT/glut.h>
#include <OpenGL/OpenGL.h>

//Initialize OpenGL 
void init(void) {
    glClearColor(0.0,0.0,0.0,0.0); 
    glMatrixMode(GL_PROJECTION); 
    gluOrtho2D(0.0,300.0,0.0,300.0);    
} 

void drawLines(void) {
    glClear(GL_COLOR_BUFFER_BIT);  
    glColor3f(0.0,0.4,0.2); 
    glPointSize(3.0);  

    glBegin(GL_LINES);
    glVertex2d(180, 15);
    glVertex2d(10, 145);
    glEnd();
} 

int main(int argc, char**argv) {
    glutInit(&argc, argv);  
    glutInitWindowPosition(10,10); 
    glutInitWindowSize(500,500); 
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); 

    glutCreateWindow("Example"); 
    init(); 
    glutDisplayFunc(drawLines); 
    glutMainLoop();
}

When I run this piece of code, I get completely blank white screen.


Solution

  • i'm also not an expert on OpenGL but the problem is that you haven't set a viewport to where your scene should be projected. Your init should look somewhat like this:

    glClearColor(0, 0, 0, 0);
    
    glViewport(0, 0, 500, 500);
    
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    
    glOrtho(0, 500, 0, 500, 1, -1);
    
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    

    You also need to put a glFlush(); after your drawing.

    void drawLines(void) {
        ...
        glFlush();
    }