Created
December 5, 2022 22:26
-
-
Save themisir/e9d3c43fe9d030bd9a4dac575f7e74de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Translated from https://github.com/leeoniya/transformation-matrix-js/blob/master/src/matrix.js | |
export class Matrix { | |
public constructor( | |
private readonly a: number, | |
private readonly b: number, | |
private readonly c: number, | |
private readonly d: number, | |
private readonly e: number, | |
private readonly f: number | |
) {} | |
public static identity = new Matrix(1, 0, 0, 1, 0, 0); | |
public transform( | |
a2: number, | |
b2: number, | |
c2: number, | |
d2: number, | |
e2: number, | |
f2: number | |
): Matrix { | |
return new Matrix( | |
this.a * a2 + this.c * b2, | |
this.b * a2 + this.d * b2, | |
this.a * c2 + this.c * d2, | |
this.b * c2 + this.d * d2, | |
this.a * e2 + this.c + f2 + this.e, | |
this.b * e2 + this.d * f2 + this.f | |
); | |
} | |
public flipX(): Matrix { | |
return this.transform(-1, 0, 0, 1, 0, 0); | |
} | |
public flipY(): Matrix { | |
return this.transform(1, 0, 0, -1, 0, 0); | |
} | |
public rotate(angle: number): Matrix { | |
const cos = Math.cos(angle), | |
sin = Math.sin(angle); | |
return this.transform(cos, sin, -sin, cos, 0, 0); | |
} | |
public rotateDeg(angle: number): Matrix { | |
return this.rotate(angle * 0.017453292519943295); | |
} | |
public scale(sx: number, sy: number): Matrix { | |
return this.transform(sx, 0, 0, sy, 0, 0); | |
} | |
public skew(sx: number, sy: number): Matrix { | |
return this.transform(1, sy, sx, 1, 0, 0); | |
} | |
public translate(tx: number, ty: number): Matrix { | |
return this.transform(1, 0, 0, 1, tx, ty); | |
} | |
public inverse(): Matrix { | |
const dt = this.a * this.d - this.b * this.c; | |
return new Matrix( | |
this.d / dt, | |
-this.b / dt, | |
-this.c / dt, | |
this.a / dt, | |
(this.c * this.f - this.d * this.e) / dt, | |
-(this.a * this.f - this.b * this.e) / dt | |
); | |
} | |
public applyTo(x: number, y: number): [number, number] { | |
return [x * this.a + y * this.c + this.e, x * this.b + y * this.d + this.f]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment