Reputation: 477
I'm trying to draw the 4 cornes of this rotated rectangle with a top left transform origin. Right now, the red rectangle is drawn exactly like I want but I'm trying to draw the fours cornes but as you can see it looks like the coordinates are shifted but I don't understand why. How can I correct the green corner coordinates so they match the red rectangle.
The x and y coordinates of the red rectangle corresponds to the rotated top left corner of the rectangle
function radians(deg) {
return deg * (Math.PI / 180);
}
function getPointRotated(X, Y, R, Xos, Yos) {
var rotatedX = X + Xos * Math.cos(radians(R)) - Yos * Math.sin(radians(R));
var rotatedY = Y + Xos * Math.sin(radians(R)) + Yos * Math.cos(radians(R));
return {
x: rotatedX,
y: rotatedY
};
}
const rect = {
x: 100,
y: 100,
width: 150,
height: 50,
rotation: 45
};
const htmlRect = document.createElement("div");
htmlRect.style.height = rect.height + "px";
htmlRect.style.width = rect.width + "px";
htmlRect.style.position = "absolute";
htmlRect.style.background = "red";
htmlRect.style.transformOrigin = "top left";
htmlRect.style.transform = `translate3d(${rect.x}px,${rect.y}px,0) rotate(${rect.rotation}deg)`;
document.body.appendChild(htmlRect);
function drawPoint(point) {
const el = document.createElement("div");
el.style.height = 10 + "px";
el.style.width = 10 + "px";
el.style.position = "absolute";
el.style.background = "green";
el.style.transformOrigin = "center center";
el.style.transform = `translate3d(${point.x}px,${point.y}px,0)`;
document.body.appendChild(el);
}
var pointRotated = [];
pointRotated.push(
getPointRotated(
rect.x,
rect.y,
rect.rotation,
-rect.width / 2,
rect.height / 2
)
);
pointRotated.push(
getPointRotated(
rect.x,
rect.y,
rect.rotation,
rect.width / 2,
rect.height / 2
)
);
pointRotated.push(
getPointRotated(
rect.x,
rect.y,
rect.rotation,
-rect.width / 2,
-rect.height / 2
)
);
pointRotated.push(
getPointRotated(
rect.x,
rect.y,
rect.rotation,
rect.width / 2,
-rect.height / 2
)
);
for (let point of pointRotated) {
drawPoint(point);
}
Upvotes: 0
Views: 757
Reputation:
A rotation around the origin follows the equation
X = c x - s y
Y = s x + c y
where c
, s
are the cosine and sine of the angle.
A rotation around an arbitrary point (u, v)
is
X = c (x - u) - s (y - v) + u
Y = s (x - u) + c (y - v) + v
Upvotes: 0