- Asked 4/25
- 2078 Bhadra · 5 marks
- 2078 Kartik · 4 marks
- 2076 Asoj · 5 marks
- 2075 Chaitra · 2 marks
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*().
| Mode | Draws |
|---|---|
| GL_POINTS | Individual points |
| GL_LINES | Separate line segments (pairs of vertices) |
| GL_LINE_STRIP / GL_LINE_LOOP | Connected lines (open / closed) |
| GL_TRIANGLES | Triangles |
| GL_QUADS | Quadrilaterals |
| GL_POLYGON | A 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)
Related questions
- OpenGL syntax: parallelogram · Computer Graphics, chapter 9
- OpenGL syntax: 3D vertex · Computer Graphics, chapter 9
- Composite rotation and shear in 2D · Computer Graphics, chapter 3
- Stagnation points in 2D velocity field · Fluid Mechanics, chapter 4
- Ruled surface between two lines: points · Computer Aided Design, chapter 4
- Percent cold work of a drawn wire · Material Science, chapter 4
- Couple, wrench, moment of P about points and lines · Applied Mechanics, chapter 3