Skip to main content

Drawing primitives in OpenGL

Short answer

Points, lines, and polygons are drawn between glBegin(mode) and glEnd(): GL_POINTS, GL_LINES, GL_LINE_STRIP, GL_LINE_LOOP, GL_TRIANGLES, GL_QUADS, GL_POLYGON. Vertices specified with glVertex*, colors with glColor*; line width and point size set by glLineWidth/glPointSize. Example: glBegin(GL_LINES); glColor3f(1,0,0); glVertex2f(...); ... glEnd();

How are points, lines and polygons drawn in OpenGL? Write the OpenGL syntax to draw basic 2D geometric primitives (coloured lines and polygons) with examples.

In OpenGL, primitives are drawn between glBegin(mode) and glEnd(), giving the vertices with glVertex*() and colours with glColor*().

ModeDraws
GL_POINTSIndividual points
GL_LINESSeparate line segments (pairs of vertices)
GL_LINE_STRIP / GL_LINE_LOOPConnected lines (open / closed)
GL_TRIANGLESTriangles
GL_QUADSQuadrilaterals
GL_POLYGONA single convex polygon

Other useful functions: glPointSize(w), glLineWidth(w), glColor3f(r,g,b) (values 0 to 1).

Example

#include <GL/glut.h>

void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);

    glPointSize(5.0f);
    glBegin(GL_POINTS);                 // points
        glColor3f(1, 1, 1);
        glVertex2f(-0.8f, 0.8f);
    glEnd();

    glLineWidth(2.0f);
    glBegin(GL_LINES);                  // coloured line
        glColor3f(1, 0, 0); glVertex2f(-0.9f, -0.9f);
        glColor3f(0, 0, 1); glVertex2f(-0.1f, -0.1f);
    glEnd();

    glBegin(GL_POLYGON);                // coloured polygon
        glColor3f(0, 1, 0); glVertex2f(0.1f, 0.1f);
        glColor3f(1, 1, 0); glVertex2f(0.8f, 0.1f);
        glColor3f(0, 1, 1); glVertex2f(0.8f, 0.8f);
        glColor3f(1, 0, 1); glVertex2f(0.1f, 0.8f);
    glEnd();
    glFlush();
}
int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutCreateWindow("Primitives");
    glutDisplayFunc(display);
    glutMainLoop();
    return 0;
}

The line goes from red to blue (colours are interpolated) and the polygon is shaded with the four vertex colours.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Graphics chapter 9 questions →