<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Matrix operations</title>
<!-- math.js library for matrix operations -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.4.3/math.js"></script>
</head>
<body>
<script>
function localRotation(x, y, xc, yc, angle) {
// Create a matrix where each row is a dimension
// First row is x, second is y, and last is z (filled with ones to allow for translation with matrix multiplication)
var coordinates = math.matrix([
x, // x values
y, // y values
math.ones(x.length) // "Homogenous coordinates addition"
]);
// Matrix for rotating
const radians = (Math.PI / 180) * angle;
const rotate = math.matrix([
[Math.cos(radians), -Math.sin(radians), 0],
[Math.sin(radians), Math.cos(radians), 0],
[0, 0, 1]
]);
// Matrix for translating the square to the origin
const translateToOrigin = math.matrix([
[1, 0, -xc],
[0, 1, -yc],
[0, 0, 1],
]);
// Matrix for translating the square back to its original position
const translateToOriginalPos = math.matrix([
[1, 0, xc],
[0, 1, yc],
[0, 0, 1],
]);
// Combine all transformations into one matrix
// The operations are in order from left to right!
// First translate square to origin, then rotate, then translate back to original position
const allTransformations = math.multiply(translateToOriginalPos, rotate, translateToOrigin);
// Apply the transformation matrix
coordinates = math.multiply(allTransformations, coordinates);
// Here you should also divide each coordinate by the last row, but I didn't find an elegant way of doing it
// It's not necessary, I think, when you only translate and rotate
// Extract the x and y coordinates and return them
const xCoordinates = coordinates._data[0];
const yCoordinates = coordinates._data[1];
return [xCoordinates, yCoordinates];
}
const squareVerticesXPos = [ 8, 12, 12, 8]; // x coordinates
const squareVerticesYPos = [-12, -12, -8, -8]; // y coordinates
const squareOriginX = 10; // x, y, z (homogenous coordinate)
const squareOriginY = -10; // x, y, z (homogenous coordinate)
const angle = 90;
const newCoordinates = localRotation(squareVerticesXPos, squareVerticesYPos, squareOriginX, squareOriginY, angle);
console.log("Starting coordinates (x,y)");
console.log(math.transpose([squareVerticesXPos, squareVerticesYPos]));
console.log("Coordinates (x,y) after transforming");
console.log(math.transpose(newCoordinates));
</script>
</body>
</html>