How To: Create an Orthographic Projection Matrix for OpenGL

This version of the code uses the Matrix4f class from LWJGL Utils, but you can obviously use any 4×4 matrix class you’d like:

// Method to create and return a 2D orthographic projection matrix 
public Matrix4f createOrthoProjectionMatrix(float left, float right, float top, float bottom, float near, float far)
	Matrix4f m = new Matrix4f();
	m.m00 = 2.0f / (right - left);
	m.m01 = 0.0f;
	m.m02 = 0.0f;
	m.m03 = 0.0f;
	m.m10 = 0.0f;
	m.m11 = 2.0f / (top - bottom);
	m.m12 = 0.0f;
	m.m13 = 0.0f;
	m.m20 = 0.0f;
	m.m21 = 0.0f;
	m.m22 = -2.0f / (far - near);
	m.m23 = 0.0f;
	m.m30 = -(right + left  ) / (right - left  );
	m.m31 = -(top   + bottom) / (top   - bottom);
	m.m32 = -(far   + near  ) / (far   - near  );
	m.m33 = 1.0f;
	return m;

To place the origin in the bottom-left corner of the window (positive y-axis pointing upwards) you’d then create a matrix like this:

Matrix4f orthographicProjectionMatrix = createOrthoProjectionMatrix(0.0f, windowWidth, windowHeight, 0.0f, -1.0f, 1.0f);

While to place the origin in the top-left corner (positive y-axis pointing downwards) then just switch the windowHeight and 0.0f to make the line:

Matrix4f orthographicProjectionMatrix = createOrthoProjectionMatrix(0.0f, windowWidth, 0.0f, windowHeight, -1.0f, 1.0f);

As a final note, for 2D graphics sitting on z = 0.0f (you can easily have a 3D orthographic projection – for example in a CAD package) we typically specify the near and far values as -1.0f to 1.0f in a right-handed coordinate system (such as OpenGL) – putting them both as 0.0f can cause issues, so its’ best not to.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.