2D Affine Transformation Matrix
A affine transformation matrix (3x3) class for JavaScript that performs
77 | various transformations such as rotate, scale, translate, skew, add, subtract
78 | and multiply.
79 | It's intended for situations where you need to track or create transforms
80 | and want to apply it permanently to your own points.
81 | The matrix can optionally synchronize a canvas 2D context object so the transformations
82 | on the canvas matches pixel perfect the local transformations of the Matrix object.
83 | No dependencies.
84 | Usage
Just include the script and create a new instance like:
85 | var matrix = new Matrix([context]);
You can supply an optional context as argument which in case will be
86 | synchronized with the transformations that are applied to the matrix
87 | object.
88 | You can now apply transformations:
89 | matrix.rotate(angle); // angle in radians
90 | matrix.rotateDeg(angle); // angle in degrees
91 | matrix.translate(x, y);
92 | matrix.translateX(x);
93 | matrix.translateY(y);
94 | matrix.scale(sx, sy);
95 | matrix.scaleX(sx);
96 | matrix.scaleY(sy);
97 | matrix.skew(sx, sy);
98 | matrix.skewX(sx);
99 | matrix.skewY(sy);
100 | matrix.transform(a, b, c, d, e, f);
101 | matrix.setTransform(a, b, c, d, e, f);
102 | matrix.reset();
Get current transform matrix values:
103 | var a = matrix.a; // scale x
104 | var b = matrix.b; // skew y
105 | var c = matrix.c; // skew x
106 | var d = matrix.d; // scale y
107 | var e = matrix.e; // translate x
108 | var f = matrix.f; // translate y
Apply to a point:
109 | var tPoint = matrix.applyToPoint(x, y);
Apply to an Array with point objects or point pair values:
110 | var tPoints = matrix.applyToArray([{x: x1, y: y1}, {x: x2, y: y2}, ...]);
111 | var tPoints = matrix.applyToArray([x1, y1, x2, y2, ...]);
112 | var tPoints = matrix.applyToTypedArray(...);
or apply to a canvas context (other than optionally referenced in constructor):
113 | matrix.applyToContext(myContext);
Get inverse transformation matrix (the matrix you need to apply to get back
114 | to a identity matrix from whatever the matrix contains):
115 | var invmatrix = matrix.getInverse();
You can interpolate between current and a new matrix. The function
116 | returns a new matrix:
117 | var imatrix = matrix.interpolate(matrix2, t); // t = [0.0, 1.0]
Check if there is any transforms applied:
118 | var status = matrix.isIdentity(); // true if identity
Check if two matrices are identical:
119 | var status = matrix.isEqual(matrix2); // true if equal
Reset matrix to an identity matrix:
120 | matrix.reset();
Methods are also chain-able:
121 | matrix.rotateDeg(45).translate(100, 120); // rotate, then translate
See documentation for full overview and usage.
122 | License
Released under MIT license. You can use this class in both commercial and non-commercial projects provided that full header (minified and developer versions) is included.
123 | © 2014 Epistmex
124 | 
125 |