glMatrix Tutorial

Matrix math is a core part of 3D graphics (though it has many other applications too!)

This page provides interactive examples of how to use glMatrix to apply various transforms to a 3D scene.

The Basics

...

Projection Matrices

A projection matrix is typically used to control your viewport into a 3D scene. Think of it as a sort of lense for your virtual camera. The two most commonly used projection matrices are "Perspective" and "Orthographic".

Perspective

function projection(out, width, height, ts) {
  var fieldOfView = Math.PI / 4; // 45 degrees 
  var aspectRatio = width / height;
  var near = 0.1;
  var far = 100.0;

  mat4.perspective(out, fieldOfView, aspectRatio, near, far);
}

Orthographic

function projection(out, width, height, ts) {
  var left = -width / 2;
  var right = width / 2;
  var top = -height / 2;
  var bottom = height / 2;
  var near = 0.0;
  var far = 100.0;

  mat4.ortho(out, left, right, bottom, top, near, far);
}

Transform Matrices

Most of the time, you'll use matrices to transform the size, shape, position, and rotation of a 3D object in a scene. glMatrix has built-in functions for many of the most common transforms, and it's easy to combine them to get the effect you need

Translate

var v = vec3.create();
function transform(out, time) {
  vec3.set(v, Math.sin(time) * 3.0, 0, Math.cos(time) * 3.0);
  mat4.translate(out, out, v);
}

Scale

var v = vec3.create();
function transform(out, time) {
  var scale = Math.sin(time) + 1.0;
  vec3.set(v, scale, scale, scale);
  mat4.scale(out, out, v);
}

Rotate

var axis = vec3.create();
function transform(out, time) {
  vec3.set(axis, 1, 1, 0);
  mat4.rotate(out, out, time, axis);
}
function transform(out, time) {
  mat4.rotateX(out, out, time);
}
function transform(out, time) {
  mat4.rotateY(out, out, time);
}
function transform(out, time) {
  mat4.rotateZ(out, out, time);
}

This project is maintained by toji and sinisterchipmunk

Hosted on GitHub Pages — Theme by orderedlist