Vector2.js is published as @rawify/vector2. It provides two-dimensional vector arithmetic, projection, rejection, reflection, refraction, rotation, interpolation, and geometric predicates.
Use it for standalone geometry, graphics, simulation, and coordinate calculations that operate on {x, y} values. Use the vector type supplied by an existing rendering or physics engine when avoiding conversions is more important than a small independent API.
Utility functions: normalization, angle, distance, rotation, linear interpolation (lerp)
Support for creating vectors from arrays or objects
Ability to work with Hadamard products, rejection from vectors, and more
Installation
You can install Vector2.js via npm:
npm install @rawify/vector2
Or with yarn:
yarn add @rawify/vector2
Alternatively, download or clone the repository:
git clone https://github.com/rawify/Vector2.js
Usage
CommonJS
const Vector2 = require('@rawify/vector2');const vector = new Vector2(1, 2);
ES modules
import Vector2, { Vector2 as NamedVector2 } from '@rawify/vector2';const vector = new Vector2(1, 2);
Standalone browser script
<script src="https://cdn.jsdelivr.net/npm/@rawify/vector2@0.0.6/dist/vector2.min.js"></script><script> const vector = new Vector2(1, 2);</script>
Native browser module
<script type="module"> import Vector2 from 'https://cdn.jsdelivr.net/npm/@rawify/vector2@0.0.6/dist/vector2.mjs'; const vector = new Vector2(1, 2);</script>
The package has no runtime dependencies and supports Node.js 20 or newer. For
backward API compatibility, both Vector2(1, 2) and new Vector2(1, 2) create
instances. CommonJS consumers can use the direct export as well as its
.default and .Vector2 aliases. These compatibility paths are covered by the
test suite and are part of the supported API.
Recipes
Decompose a vector into parallel and perpendicular parts
Projection and rejection return components whose sum reconstructs the original vector.
import Vector2 from '@rawify/vector2';const vector = new Vector2(3, 4);const axis = new Vector2(1, 0);const parallel = vector.projectTo(axis);const perpendicular = vector.rejectFrom(axis);console.log(parallel.toArray()); // [3, 0]console.log(perpendicular.toArray()); // [0, 4]console.log(parallel.add(perpendicular).toArray()); // [3, 4]
The projection axis must be non-zero; projecting onto (0, 0) divides by zero and produces non-finite components.
Rotate a direction and locate a barycentric point
Angles are measured in radians. Barycentric inputs use A + u(B - A) + v(C - A).
import Vector2 from '@rawify/vector2';const rotated = new Vector2(1, 0).rotate(Math.PI / 2);const point = Vector2.fromBarycentric( new Vector2(0, 0), new Vector2(10, 0), new Vector2(0, 10), 0.2, 0.3);console.log(rotated.toArray().map((n) => +n.toFixed(12))); // [0, 1]console.log(point.toArray()); // [2, 3]
The barycentric method does not require u + v <= 1; values outside the triangle extrapolate.
Choose immutable or in-place arithmetic
Ordinary arithmetic methods return a new vector. Methods ending in $ mutate and return the receiver.
import Vector2 from '@rawify/vector2';const original = new Vector2(3, 4);const doubled = original.scale(2);const mutable = original.clone().scale$(2);console.log(original.toArray()); // [3, 4]console.log(doubled.toArray()); // [6, 8]console.log(mutable.toArray()); // [6, 8]
set() also mutates and returns undefined. normalize() usually creates a vector, but returns the same instance for a zero or already-unit vector; use clone() when identity matters.
Creating a Vector
Vectors can be created using new Vector2 or the Vector2 function:
let v1 = Vector2(1, 2);let v2 = new Vector2(3, 4);
You can also initialize vectors from arrays or objects:
let v3 = new Vector2([1, 2]);let v4 = new Vector2({ x: 3, y: 4 });
Methods
add(v)
Adds the vector v to the current vector.
let v1 = new Vector2(1, 2);let v2 = new Vector2(3, 4);let result = v1.add(v2); // {x: 4, y: 6}
sub(v)
Subtracts the vector v from the current vector.
let result = v1.sub(v2); // {x: -2, y: -2}
neg()
Negates the current vector (flips the direction).
let result = v1.neg(); // {x: -1, y: -2}
scale(s)
Scales the current vector by a scalar s.
let result = v1.scale(2); // {x: 2, y: 4}
prod(v)
Calculates the Hadamard (element-wise) product of the current vector and v.
let result = v1.prod(v2); // {x: 3, y: 8}
dot(v)
Computes the dot product between of the current vector and v.
let result = v1.dot(v2); // 11
cross(v)
Calculates the 2D cross product (perpendicular dot product) between the current vector and v.
Projects the current vector onto the vector v using vector projection.
let result = v1.projectTo(v2); // Projection of v1 onto v2
rejectFrom(v)
Finds the orthogonal vector rejection of the current vector from the vector v.
let result = v1.rejectFrom(v2); // Rejection of v1 from v2
reflect(n)
Determines the vector reflection of the current vector across the vector n.
let n = new Vector2(0, 1);let result = v1.reflect(n); // Reflection of v1 across n
refract(n, eta)
Determines the vector refraction of the current unit vector across a surface with unit normaln, using the index ratio eta = η_in / η_out (like from air η_in=1.0 to water η_out=1.33).
let n = new Vector2(0, 1); // Surface normal pointing uplet eta = 1.0 / 1.33; // Air to glasslet result = v1.refract(n, eta); // Refraction of v1 across n
Returns a new unit vector representing the refracted direction, or null if total internal reflection occurs.
angle()
Returns the angle of the current vector in radians relative to the x-axis.
let result = v1.angle(); // 1.107 radians
norm()
Returns the magnitude or length (Euclidean norm) of the current vector.
let result = v1.norm(); // 2.236
norm2()
Returns the squared magnitude or length (norm squared) of the current vector.
let result = v1.norm2(); // 5
normalize()
Returns a normalized vector (unit vector) of the current vector.
let result = v1.normalize(); // {x: 0.447, y: 0.894}
distance(v)
Calculates the Euclidean distance between the current vector and v.
let result = v1.distance(v2); // 2.828
set(v)
Sets the values of the current vector to match the vector v.
v1.set(v2); // v1 is now {x: 3, y: 4}
rotate(angle)
Rotates the current vector by the given angle (in radians).
let result = v1.rotate(Math.PI / 4); // Rotates v1 by 45 degrees
apply(fn, v)
Applies a function fn (such as Math.abs, Math.min, Math.max) to the components of the current vector and an optional vector v.
let result1 = v1.apply(Math.min, v2); // Determines the minimum of v1 and v2 on each componentlet result2 = v1.apply(Math.max, v2); // Determines the maximum of v1 and v2 on each componentlet result3 = v1.apply(Math.round); // Rounds the components of the vectorlet result4 = v1.apply(Math.floor); // Floors the components of the vectorlet result4 = v1.apply(x => Math.min(upper, Math.max(lower, x))); // Clamps the component to the interval [lower, upper]
toArray()
Returns the current vector as an array [x, y].
let result = v1.toArray(); // [1, 2]
clone()
Returns a clone of the current vector.
let result = v1.clone(); // A new vector with the same x and y values as v1
equals(v)
Checks if the current vector is equal to the vector v.
let result = v1.equals(v2); // false
isParallel(v)
Checks if the current vector is parallel zu vector v.
isUnit()
Checks if the current vector is a normalized unit vector.
lerp(v, t)
Performs a linear interpolation between the current vector and v by the factor t.
let result = v1.lerp(v2, 0.5); // {x: 2, y: 3}
toString()
String representation of the current vector
Static Methods
Vector2.random()
Generates a vector with random x and y values between 0 and 1.
let randomVector = Vector2.random(); // {x: 0.67, y: 0.45}
Vector2.fromPoints(a, b)
Creates a vector from two points a and b.
let result = Vector2.fromPoints({x: 1, y: 1}, {x: 4, y: 5}); // {x: 3, y: 4}
Vector2.fromBarycentric(A, B, C, u, v)
Given a triangle (A, B, C) and a barycentric coordinate (u, v[, w = 1 - u - v]) calculate the cartesian coordinate in R^2.
Building the library
The implementation is written in strict TypeScript. The build emits CommonJS,
ES modules, a standalone browser bundle, source maps, and format-specific type
declarations without modifying source or documentation files.
After cloning the Git repository, run:
npm installnpm run build
Run a test
Testing the source against the shipped test suite is as easy as
npm run test
Copyright and Licensing
Copyright (c) 2025, Robert Eisele
Licensed under the MIT license.