Created
September 22, 2024 21:46
-
-
Save davidbalbert/15864a7baeb914e70c47472aa251c4bc to your computer and use it in GitHub Desktop.
An affine transform for JavaScript. Saved for later.
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
// an affine transformation matrix | |
class AffineTransform { | |
// the matrix is represented as a 3x3 matrix | |
// | A C Tx | | |
// | B D Ty | | |
// | 0 0 1 | | |
// A, B, C, D are the coefficients of the linear transformation | |
// Tx, Ty are the translation components | |
constructor(A, C, Tx, B, D, Ty) { | |
this.A = A; | |
this.C = C; | |
this.Tx = Tx; | |
this.B = B; | |
this.D = D; | |
this.Ty = Ty; | |
} | |
mul(other) { | |
const m = this; | |
const n = other; | |
const a = m.A*n.A + m.C*n.B; | |
const c = m.A*n.C + m.C*n.D; | |
const tx = m.A*n.Tx + m.C*n.Ty + m.Tx; | |
const b = m.B*n.A + m.D*n.B; | |
const d = m.B*n.C + m.D*n.D; | |
const ty = m.B*n.Tx + m.D*n.Ty + m.Ty; | |
this.A = a; | |
this.C = c; | |
this.Tx = tx; | |
this.B = b; | |
this.D = d; | |
this.Ty = ty; | |
} | |
translate(tx, ty) { | |
this.mul(Translation(tx, ty)); | |
} | |
rotate(angle) { | |
this.mul(Rotation(angle)); | |
} | |
rotateDegrees(degrees) { | |
this.mul(RotationDegrees(degrees)); | |
} | |
scale(sx, sy) { | |
this.mul(Scale(sx, sy)); | |
} | |
shear(kx, ky) { | |
this.mul(Shear(kx, ky)); | |
} | |
} | |
function Id() { | |
return new AffineTransform(1, 0, 0, 0, 1, 0); | |
} | |
function Translation(tx, ty) { | |
return new AffineTransform(1, 0, tx, 0, 1, ty); | |
} | |
function Rotation(angle) { | |
const cos = Math.cos(angle); | |
const sin = Math.sin(angle); | |
return new AffineTransform(cos, -sin, 0, sin, cos, 0); | |
} | |
function RotationDegrees(degrees) { | |
return Rotation(degrees * Math.PI / 180); | |
} | |
function Scale(sx, sy) { | |
return new AffineTransform(sx, 0, 0, 0, sy, 0); | |
} | |
function Shear(kx, ky) { | |
return new AffineTransform(1, kx, 0, ky, 1, 0); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment