Calculate coordinates of a point with transformation matrix
by cancerbero_sgx
July 10, 2019
HTML
<p>
The blue polygon has the same points as the green one + transformation
<br>
Coordinates of the red circles are calculated with transformation matriсes
</p>
<svg height="1000" width="1000" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000"></svg>s
CSS
circle {
fill: red;
r: 4px;
}
polygon {
fill: #d6ffd6;
stroke: green;
stroke-width: 1px;
}
polygon[transform] {
fill: #d6e1ff;
stroke: blue;
}
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 polygonPoints = [
{x: 100, y: 50},
{x: 175, y: 100},
{x: 50, y: 200},
{x: 25, y: 75},
];
let transformMatrix = multiplyMatrices(multiplyMatrices(translationMatrix, scalingMatrix), rotationMatrix);
let svgElem = document.querySelector('svg');
let polygonElem = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
let transformedPolygonElem = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
let pointsAttribute = polygonPoints.reduce((previousValue, point) => {
return previousValue + ` ${point.x},${point.y}`;
}, '');
polygonElem.setAttribute('points', pointsAttribute);
transformedPolygonElem.setAttribute('points', pointsAttribute);
svgElem.appendChild(polygonElem);
svgElem.appendChild(transformedPolygonElem);
transformedPolygonElem.setAttribute('transform', `translate(${translation.x}, ${translation.y}) scale(${scaling.x}, ${scaling.y}) rotate(${angleInDegrees})`);
polygonPoints.forEach((point) => {
let pointMatrix =...