1 | import { radiansToDegrees, degreesToRadians } from '../utils/number-utils';
|
2 | export const getTransformMatrix = ({ property, value }) => TRANSFORM_MATRIXES[property](value);
|
3 | const TRANSFORM_MATRIXES = {
|
4 | scale: ({ x, y }) => [x, 0, 0, 0, y, 0, 0, 0, 1],
|
5 | translate: ({ x, y }) => [1, 0, x, 0, 1, y, 0, 0, 1],
|
6 | rotate: ({ x, y, z }) => {
|
7 |
|
8 | const radZ = degreesToRadians(z);
|
9 | const cosZ = Math.cos(radZ);
|
10 | const sinZ = Math.sin(radZ);
|
11 | return [cosZ, -sinZ, 0, sinZ, cosZ, 0, 0, 0, 1];
|
12 | },
|
13 | };
|
14 | export const matrixArrayToCssMatrix = (m) => [m[0], m[3], m[1], m[4], m[2], m[5]];
|
15 | export function multiplyAffine2d(m1, m2) {
|
16 | return [m1[0] * m2[0] + m1[1] * m2[3], m1[0] * m2[1] + m1[1] * m2[4], m1[0] * m2[2] + m1[1] * m2[5] + m1[2], m1[3] * m2[0] + m1[4] * m2[3], m1[3] * m2[1] + m1[4] * m2[4], m1[3] * m2[2] + m1[4] * m2[5] + m1[5]];
|
17 | }
|
18 |
|
19 | export function decompose2DTransformMatrix(matrix) {
|
20 | verifyTransformMatrix(matrix);
|
21 | const [A, B, C, D, E, F] = [...matrix];
|
22 | const determinant = A * D - B * C;
|
23 | const translate = { x: E || 0, y: F || 0 };
|
24 |
|
25 | let rotate = 0;
|
26 | let scale = { x: 1, y: 1 };
|
27 | if (A || B) {
|
28 | const R = Math.sqrt(A * A + B * B);
|
29 | rotate = B > 0 ? Math.acos(A / R) : -Math.acos(A / R);
|
30 | scale = { x: R, y: determinant / R };
|
31 | }
|
32 | else if (C || D) {
|
33 | const R = Math.sqrt(C * C + D * D);
|
34 | rotate = Math.PI / 2 - (D > 0 ? Math.acos(-C / R) : -Math.acos(C / R));
|
35 | scale = { x: determinant / R, y: R };
|
36 | }
|
37 | rotate = radiansToDegrees(rotate);
|
38 | return { translate, rotate: { x: 0, y: 0, z: rotate }, scale };
|
39 | }
|
40 | function verifyTransformMatrix(matrix) {
|
41 | if (matrix.length < 6) {
|
42 | throw new Error('Transform matrix should be 2x3.');
|
43 | }
|
44 | }
|
45 |
|
\ | No newline at end of file |