Skip to main content

Callback function with example

Short answer

Callback functions are registered via GLUT (e.g., glutDisplayFunc, glutKeyboardFunc) and called automatically on events. In an example, a display callback redraws a colored square, a keyboard callback exits on 'q', and a mouse callback changes the color and requests redisplay with glutPostRedisplay, driven by glutMainLoop.

Explain the callback function with example in OpenGL.

A callback function is a user-defined function that is registered with GLUT (glutXxxFunc) and is called automatically by the library when a specific event happens (redraw, key press, mouse click, window resize, idle time). Because of this, an OpenGL program is event driven: glutMainLoop() waits for events and calls the proper callback.

Common callbacks: glutDisplayFunc (draw), glutReshapeFunc (resize), glutKeyboardFunc (keys), glutMouseFunc (mouse buttons), glutIdleFunc (animation), glutTimerFunc.

Example: a square that changes colour with a mouse click and closes with the 'q' key

#include <GL/glut.h>
#include <stdlib.h>

float r = 1, g = 0, b = 0;

void display(void) {                       // display callback
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(r, g, b);
    glBegin(GL_QUADS);
        glVertex2f(-0.5f, -0.5f); glVertex2f(0.5f, -0.5f);
        glVertex2f(0.5f, 0.5f);   glVertex2f(-0.5f, 0.5f);
    glEnd();
    glFlush();
}
void mouse(int button, int state, int x, int y) {   // mouse callback
    if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
        r = (float)rand() / RAND_MAX;
        g = (float)rand() / RAND_MAX;
        b = (float)rand() / RAND_MAX;
        glutPostRedisplay();               // ask GLUT to call display again
    }
}
void keyboard(unsigned char key, int x, int y) {    // keyboard callback
    if (key == 'q') exit(0);
}
int main(int argc, char **argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutCreateWindow("Callback demo");
    glutDisplayFunc(display);              // register callbacks
    glutMouseFunc(mouse);
    glutKeyboardFunc(keyboard);
    glutMainLoop();
    return 0;
}

Each left click calls mouse, which changes the colour and requests a redraw; GLUT then calls display.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Graphics chapter 9 questions →