Skip to content

Instantly share code, notes, and snippets.

@kolosovsky
Last active May 20, 2018 10:39
Show Gist options
  • Save kolosovsky/2214716328d15f851833696653913a18 to your computer and use it in GitHub Desktop.
Save kolosovsky/2214716328d15f851833696653913a18 to your computer and use it in GitHub Desktop.
Transformation matrix in JavaScript

Transformation matrix in JavaScript

function multiplyMatrices(matrixA, matrixB) {
  let aNumRows = matrixA.length;
  let aNumCols = matrixA[0].length;
  let bNumRows = matrixB.length;
  let bNumCols = matrixB[0].length;
  let newMatrix = new Array(aNumRows);

  for (let r = 0; r < aNumRows; ++r) {
    newMatrix[r] = new Array(bNumCols);

    for (let c = 0; c < bNumCols; ++c) {
      newMatrix[r][c] = 0;

      for (let i = 0; i < aNumCols; ++i) {
        newMatrix[r][c] += matrixA[r][i] * matrixB[i][c];
      }
    }
  }

  return newMatrix;
}

let translation = {
  x: 200,
  y: 50
};
let scaling = {
  x: 1.5,
  y: 1.5
};
let angleInDegrees = 25;
let angleInRadians = angleInDegrees * (Math.PI / 180);
let translationMatrix = [
  [1, 0, translation.x],
  [0, 1, translation.y],
  [0, 0, 1],
];
let scalingMatrix = [
  [scaling.x, 0, 0],
  [0, scaling.y, 0],
  [0, 0, 1],
];
let rotationMatrix = [
  [Math.cos(angleInRadians), -Math.sin(angleInRadians), 0],
  [Math.sin(angleInRadians), Math.cos(angleInRadians), 0],
  [0, 0, 1],
];
let transformMatrix = multiplyMatrices(multiplyMatrices(translationMatrix, scalingMatrix), rotationMatrix);
let originalCoordinates = { x: 100, y: 200 }; // coordinates before transformation
let resultMatrix = multiplyMatrices(transformMatrix, [[originalCoordinates.x], [originalCoordinates.y], [1]]);
let newCoordinates = { // coordinates after transformation
    x: resultMatrix[0],
    y: resultMatrix[1],
  };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment