glMatrix
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
-
ReferenceError: require is not defined
cause Attempting to use `gl-matrix` with CommonJS `require()` syntax or in a CommonJS module when the package is now ESM-only (since v3.4.4).fixUpdate your project to use ES Module `import` syntax (`import { mat4 } from 'gl-matrix';`) and ensure your Node.js environment or bundler correctly handles ESM. For Node.js, this often means adding `"type": "module"` to your `package.json` or using the `.mjs` file extension for the importing file. -
Uncaught ReferenceError: mat4 is not defined
cause In a browser environment, `dist/gl-matrix.js` was included via a `<script>` tag, but functions were called directly (e.g., `mat4.create()`) without using the `glMatrix` global object wrapper (introduced in v3.0.0).fixAccess functions via the `glMatrix` global object: `glMatrix.mat4.create()` instead of `mat4.create()`. Alternatively, use ES Module imports with a bundler for modern browser development. -
Property 'create' does not exist on type 'typeof import("gl-matrix/dist/gl-matrix")' or 'Type 'Float32Array' is not assignable to type 'number[]''cause TypeScript type mismatches when using older versions of `gl-matrix` without official types or with an outdated `@types/gl-matrix` package, or incorrect type assertions.fixEnsure `gl-matrix` is at least `v3.2.0` for integrated type definitions. If using older versions, verify that `@types/gl-matrix` is installed and compatible. When declaring array types, remember gl-matrix defaults to `Float32Array` (`import type { vec3 } from 'gl-matrix';` will correctly infer this). -
Error: Cannot use 'import.meta' outside a module
cause This error occurs in Node.js when `gl-matrix` (an ESM module since v3.4.4) is imported into a file that Node.js interprets as CommonJS (e.g., a `.js` file without `"type": "module"` in `package.json`). `import.meta` is an ESM-specific feature used internally by gl-matrix.fixEnsure the file importing `gl-matrix` is also treated as an ES Module by Node.js. This typically means adding `"type": "module"` to your project's `package.json` or using the `.mjs` file extension for the importing file.
Warnings
- breaking Starting with `v3.4.4`, gl-matrix explicitly transitioned to being an ES Module (`"type": "module"` in `package.json`). This means that CommonJS `require()` statements will generally no longer work out-of-the-box and require explicit ESM support in your environment.
- breaking In `v3.0.0`, the global namespace handling for direct `<script>` includes changed. Instead of polluting the global scope with individual functions like `vec2`, `mat4`, etc., all functionality is now exposed under a single global `glMatrix` object (e.g., `glMatrix.mat4.create()`).
- gotcha Version `3.4.0` was briefly published to npm with a breaking change related to Node.js module handling and then quickly deprecated in favor of `3.4.1` to avoid the breakage. Developers who accidentally installed `3.4.0` would have encountered issues.
- gotcha While gl-matrix defaults to using `Float32Array` for performance, the library allows overriding this behavior with `glMatrix.setMatrixArrayType(Array)`. However, using standard JavaScript `Array`s can sometimes *decrease* performance in modern web browsers, contrary to older advice, due to `Float32Array` optimizations in VM engines.
- gotcha Prior to `v3.2.0`, `gl-matrix` did not ship TypeScript type definitions (`.d.ts` files) directly with the package. This meant users had to rely on `@types/gl-matrix` from DefinitelyTyped, which might not always perfectly align with the library's version or latest features.
Install
-
npm install gl-matrix -
yarn add gl-matrix -
pnpm add gl-matrix
Imports
- mat4
const mat4 = require('gl-matrix').mat4;import { mat4 } from 'gl-matrix'; - vec2 (cherry-picked module)
import { create } from 'gl-matrix/vec2';import * as vec2 from 'gl-matrix/vec2';
- glMatrix (global object)
<script src="path/to/dist/gl-matrix.js"></script> <script> const matrix = mat4.create(); </script>
<script src="path/to/dist/gl-matrix.js"></script> <script> const matrix = glMatrix.mat4.create(); </script>
- Mat4 (TypeScript Type)
import type { mat4 as Mat4Type } from 'gl-matrix';
Quickstart
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);