Vectors and Matrices in JavaScript
Vectors and matrices are core concepts in linear algebra and play a central role in many JavaScript applications, particularly in graphics, animation, simulations, and game development. Understanding how to represent and manipulate vectors and matrices in JavaScript provides a strong mathematical foundation for working with coordinate systems, transformations, and motion in two and three dimensions.
This page introduces vectors and matrices in JavaScript and demonstrates how common vector and matrix operations can be implemented directly in code. The emphasis is on clarity and mathematical correctness rather than reliance on external libraries, making the techniques suitable for learning and educational use.
Understanding Vectors and Matrix Operations in JavaScript
In programming, a matrix is often represented as an "array within an array." Mastery of JavaScript matrix operations allows you to perform rotations, scaling, and translations in 2D and 3D space programmatically.
Defining Your Data Structures
To begin, we represent our mathematical objects as standard JavaScript arrays. A vector is treated as a specific type of matrix—one with a single column.
- Scalar: A single numerical value.
- Vector: A list of numbers representing magnitude and direction.
- Matrix: A rectangular grid of numbers arranged in rows and columns.
Representing Vectors in JavaScript
In JavaScript, vectors are commonly represented using arrays or simple objects. A vector may describe a position, displacement, velocity, or direction, depending on the context in which it is used.
For example, a two-dimensional vector can be stored as an array containing its components along the x- and y-axes. This representation allows standard vector operations in JavaScript, such as addition, subtraction, and scaling, to be implemented using straightforward functions.
Working with vectors in this way helps reinforce the connection between linear algebra concepts and practical JavaScript programming.
Vector Operations in JavaScript
Basic vector operations form the foundation for more advanced mathematical techniques used in graphics and animation.
Common vector operations include:
- Vector addition and subtraction
- Scalar multiplication
- Calculating magnitude (length)
- Normalising a vector
Implementing these vector operations in JavaScript allows programmers to model motion, forces, and directional changes accurately. These techniques are especially useful in canvas-based graphics and interactive applications where precise control over movement is required.
Representing Matrices in JavaScript
Matrices extend vector ideas and are essential for handling transformations such as rotation, scaling, and translation. In JavaScript, matrices are typically represented as two-dimensional arrays, where each inner array corresponds to a row of the matrix.
This approach closely mirrors the mathematical definition of a matrix and makes it easier to translate linear algebra formulas directly into JavaScript code. It also prepares students for more advanced topics such as matrix multiplication and coordinate transformations.
Matrix Operations in JavaScript
Matrix operations in JavaScript allow complex transformations to be expressed concisely and applied consistently.
Typical matrix operations include:
- Matrix addition and subtraction
- Matrix multiplication
- Multiplying a matrix by a vector
- Calculating determinants and inverses (for square matrices)
Since matrices can be represented as arrays of arrays. With JavaScript, you can easily perform:
- Matrix Addition and Subtraction - Combine or reduce values element by element.
- Matrix Multiplication - Essential for scaling, rotating, and skewing objects in graphics.
- Determinant and Inverse Matrix - Useful for solving systems of equations and advanced transformations.
Example: JavaScript Algorithm for Multiplication of Matrices >>>
These matrix operations are central to linear algebra and are widely used in computer graphics, physics simulations, and game engines. Implementing them manually in JavaScript strengthens understanding of both the mathematics and the underlying algorithms.
Vectors as Matrices
Vectors can be treated as single-row or single-column matrices. This makes it easy to apply linear algebra techniques in JavaScript:
- Representing points in 2D and 3D space.
- Performing dot products and cross products.
- Applying transformations for animations and simulations.
Image Manipulation with Matrices
Beyond math, matrices are widely used in JavaScript image manipulation. By applying matrix operations, you can:
- Rotate images clockwise or counterclockwise.
- Scale pictures up or down.
- Skew and mirror graphics for creative effects.
- Combine with HTML Canvas or SVG graphics for dynamic rendering.
Using Vectors and Matrices for Graphics
Vectors and matrices are particularly important in web graphics, including HTML5 canvas and SVG. Vectors can represent positions and directions, while matrices are used to apply transformations such as rotation, scaling, and reflection.
For example, a transformation matrix can be used to rotate a shape about the origin or scale an object uniformly across the screen. Combining vector and matrix techniques allows complex graphical effects to be achieved using relatively simple JavaScript code.
Example: JavaScript Algorithm for rotation of vectors using a rotation matrix on a 2D plane >>>
Understanding these ideas also provides a solid introduction to the mathematics behind animation, game development, and computer graphics more generally.
Educational Focus and Further Study
The methods presented here are intended for educational use at a tertiary level. By coding vectors and matrices directly in JavaScript, students gain a deeper appreciation of linear algebra concepts and how they are applied in real programming contexts.
An obvious improvement and practice exercise or fun activity is including checks in the JavaScript algorithm to make sure the supplied matrices meet the dimensional requirement for matrix multiplication.
Once these fundamentals are understood, learners can more confidently move on to advanced topics such as transformation pipelines, three-dimensional graphics, and specialised JavaScript libraries that build upon the same mathematical principles.
Practical Applications
- Web Development: Enhance animations and transitions with matrix transformations.
- Game Design: Use vectors and matrices for physics simulations and character movement.
- Educational Projects: Build interactive math tutorials and visualizations.
Summary: Vectors and Matrices in JavaScript
Vectors and matrices are fundamental tools in mathematics and computer science. In JavaScript, they provide a powerful way to perform matrix operations and vector calculations that support everything from graphics transformations to image manipulation. This tutorial explored how to implement matrix addition, subtraction, multiplication, determinants, and inverses directly in JavaScript.
- Vectors and matrices are fundamental tools in JavaScript programming for graphics and simulations
- JavaScript arrays provide a clear and effective way to represent vectors and matrices
- Implementing vector and matrix operations reinforces linear algebra concepts
- These techniques form the mathematical basis of canvas graphics, animation, and game development
Mastering vectors and matrices in JavaScript opens the door to advanced graphics transformations, image manipulation, and mathematical problem solving. Whether you’re a student learning linear algebra or a developer building interactive web applications, these concepts are essential for creating dynamic, visually engaging projects.
JavaScript Code for Multiplication of Matrices - .html
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Matrix Multiplication</title>
<script src="MultiplyMatrix.js"></script>
</head>
<body>
<h3>Multiplication of Matrices</h3>
<!-- This is where the result will be displayed when it is ready.-->
<div id="matrix_multiplied"></div>
<script>
let matrix_A = [
[5, 0, 2],
[1, 3, 8],
[6, 1, 4]
];
let matrix_B = [
[2, 0, 0],
[0, 2, 0],
[0, 0, 2]
];
const result = multiplyMatrices(matrix_A, matrix_B);
// print style inherently assumes same dimension for matrices A, B and result
let print_result = "[ ";
print_result += " ";
print_result += "[ ";
print_result += " [";
let rows_centre = Math.ceil(result.length / 2) - 1;
for (let i = 0; i < result.length; i++) {
print_result += "<br/> [" + matrix_A[i].join(", ") + "]";
if (i === rows_centre) {
print_result += " X ";
} else {
print_result += " ";
}
print_result += " [" + matrix_B[i].join(", ") + "]";
if (i === rows_centre) {
print_result += " = ";
} else {
print_result += " ";
}
print_result += " [" + result[i].join(", ") + "]";
}
print_result += "<br/>] ";
print_result += " ";
print_result += "] ";
print_result += " ]";
document.getElementById("matrix_multiplied").innerHTML = print_result;
</script>
</body>
</html>
JavaScript Code for Multiplication of Matrices - .js
// Matrix multiplication in JavaScript
// Follows same steps as you would do on paper
/*
* Warning: No checks have been done to ensure the
* dimension of both matrices are in order for multiplication
*/
function multiplyMatrices(a, b) {
let result = [];
for (let i = 0; i < a.length; i++) {
result[i] = [];
for (let j = 0; j < b[0].length; j++) {
let sum = 0;
for (let k = 0; k < b.length; k++) {
sum += a[i][k] * b[k][j];
}
result[i][j] = sum;
}
}
return result;
}
JavaScript Code for Rotation of Matrices - .html
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Matrix Rotation</title>
<script src="MultiplyMatrix.js"></script>
<script src="RotateMatrix.js"></script>
</head>
<body>
<h3>Rotation of Matrices</h3>
<!-- This is where the result will be displayed when it is ready.-->
<div id="matrix_multiplied"></div>
<script>
let vector_A = [
[9], // x-coordinate
[5], // y-coordinate
[0], // z-coordinate - use zero(0) for 2D special systems
[1] // balance for 4x4 rotation matrix
];
let angle = -90;
const result = rotateMatrix(vector_A, angle);
// do a formatted print style
let spacing_span = " ";
spacing_span += " ";
spacing_span += " ";
let spacing = spacing_span;
let print_result = spacing;
print_result += "[ ";
print_result += " [<br/>";
let rows_centre = Math.ceil(result.length / 2) - 1;
for (let i = 0; i < result.length; i++) {
if (i === rows_centre) {
print_result += "A " + angle + " rotation of ";
spacing = " ";
} else {
spacing = spacing_span;
}
print_result += spacing + " [" + vector_A[i].join(", ") + "]";
if (i === rows_centre) {
print_result += " = ";
} else {
print_result += " ";
}
print_result += " [" + result[i].join(", ") + "]<br/>";
}
print_result += spacing;
print_result += "] ";
print_result += " ]";
document.getElementById("matrix_multiplied").innerHTML = print_result;
</script>
</body>
</html>
JavaScript Code for Rotation of Matrices - .js
// Matrix rotation in JavaScript
function rotateMatrix(matrix, angle) {
const angle_in_radians = angle * (Math.PI / 180);
// 3D rotation matrix - the extra zeroes (0) and ones (1) are there for unity matrix balance
const rotation_matrix = [
[Math.cos(angle_in_radians), -Math.sin(angle_in_radians), 0, 0],
[Math.sin(angle_in_radians), Math.cos(angle_in_radians), 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]
];
return multiplyMatrices(rotation_matrix, matrix);
}
Graphics and Animations References:
For a head-start on OpenGL, please see the following links:
W3Schools Tutorials
- very precise and well written; Perfect for all.
Check out the CSS tutorials on animations, transitions and transformations; the SVG tutorials
on graphics, and the Canvas tutorials on sprites.