Installing and Using the OpenGL Component in Lazarus

The OpenGL component is not installed in Lazarus by default. This page provides instructions for installing it and testing it with a short 2D graphics form-based application.

  1. Select menu item Package > Install/Uninstall Packages....
  2. Select lazopenglcontext 0.0.1 and click the Install selection button.
    The package name will appear in the left panel of the dialogue.
  3. Click the Save and rebuild IDE button and then the Continue button to confirm the instruction. Wait for the rebuild to complete.
    Lazarus will restart with the new OpenGL component tab in place.
  4. Select menu item Project > New Project... then select Application.
  5. Select menu item File > Save All then save the project as LCL_OpenGL and the unit as uLCL_OpenGL.
  6. Select the OpenGL component tab and double click on the icon.
  7. Drag the bottom right corner of the OpenGL control so that the control occupies most of the form.
  8. In the Object Inspector, double click in the OnPaint event edit box.
  9. Replace the code of the unit with this:
    unit uLCL_OpenGL;
    
    {$mode objfpc}{$H+}
    
    interface
    
    uses
      Classes, SysUtils, FileUtil, OpenGLContext, Forms, Controls, Graphics, Dialogs, GL, GLU;
    type
      TForm1 = class(TForm)
        OpenGLControl1: TOpenGLControl;
        procedure OpenGLControl1Paint(Sender: TObject);
      end;
    
    var
      Form1: TForm1;
    
    implementation
    
    {$R *.lfm}
    
    procedure TForm1.OpenGLControl1Paint(Sender: TObject);
    begin
      glClearColor (1.0, 1.0, 1.0, 1.0); // white background
      glMatrixMode(GL_PROJECTION);
      glLoadIdentity;
      gluOrtho2D(0, 200, 0, 200);
      glClear(GL_COLOR_BUFFER_BIT);
      glColor3f (1.0, 0.0, 0.0);  // red
      glBegin(GL_POLYGON);
        // Irregular convex pentagon
        glVertex2i(5, 155);
        glVertex2i(10, 190);
        glVertex2i(40, 180);
        glVertex2i(175, 75);
        glVertex2i(50, 20);
      glEnd;
      OpenGLControl1.SwapBuffers;
    end;
    
    end.    
    
  10. Execute the application.
    You should see a window with a red irregular pentagon on a white background.
Programming - a skill for life!

How to use OpenGL for 2D and 3D graphics