glMatrix

3.4.4 · active · verified Sun Apr 19

glMatrix is a high-performance JavaScript library for vector and matrix mathematics, specifically optimized for real-time 3D graphics applications like those built with WebGL. It leverages `Float32Array` by default for numerical operations, ensuring maximum performance by minimizing garbage collection and memory overhead. The current stable version is 3.4.4, with releases occurring periodically to address bug fixes, introduce performance improvements, and maintain compatibility with modern JavaScript and TypeScript environments. Key differentiators include its focus on raw speed, a comprehensive set of operations for `vec2`, `vec3`, `vec4`, `mat3`, `mat4`, and `quat` types, and its design to prevent global namespace pollution by using named imports or a single `glMatrix` global object. It also supports cherry-picking individual modules for better tree-shaking.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic setup of projection and view matrices for a 3D scene, along with common model matrix transformations like translation and rotation using `mat4` and `vec3`.

import { mat4, vec3 } from 'gl-matrix';

/**
 * Sets up a basic camera's projection and view matrices.
 * @param {mat4} projectionMatrix The matrix to store the projection results.
 * @param {mat4} viewMatrix The matrix to store the view results.
 * @param {number} aspectRatio The aspect ratio of the viewport (width / height).
 */
function setupCamera(projectionMatrix: mat4, viewMatrix: mat4, aspectRatio: number): void {
  // Create a perspective projection matrix (Field of View, Aspect, Near, Far)
  mat4.perspective(projectionMatrix, Math.PI / 4, aspectRatio, 0.1, 100.0);

  // Create a view matrix (camera position, target, up vector)
  const cameraPosition = vec3.fromValues(0, 0, 5);
  const target = vec3.fromValues(0, 0, 0);
  const up = vec3.fromValues(0, 1, 0);
  mat4.lookAt(viewMatrix, cameraPosition, target, up);

  console.log('Initialized Projection Matrix:', projectionMatrix);
  console.log('Initialized View Matrix:', viewMatrix);
}

const projection = mat4.create();
const view = mat4.create();
setupCamera(projection, view, window.innerWidth / window.innerHeight);

// Example: Create a model matrix for an object and apply transformations
const modelMatrix = mat4.create();
const translationVector = vec3.fromValues(1, 0.5, 0);
mat4.translate(modelMatrix, modelMatrix, translationVector); // Translate by (1, 0.5, 0)

const rotationAxis = vec3.fromValues(0, 1, 0); // Rotate around Y axis
mat4.rotate(modelMatrix, modelMatrix, Math.PI / 4, rotationAxis); // Rotate 45 degrees

console.log('Model Matrix (translated and rotated):', modelMatrix);

// To reset the matrix to identity:
mat4.identity(modelMatrix);
console.log('Model Matrix (reset to identity):', modelMatrix);

view raw JSON →