【发布时间】:2019-11-29 03:25:35
【问题描述】:
如何获得旋转矩形的角坐标(以矩形的中心为轴心)?
我已经尝试了下面链接中的所有解决方案,但似乎没有任何运气。
Rotating a point about another point (2D)
Find corners of a rotated rectangle given its center point and rotation
这是代码
// make a rectangle with zero rotation
const rect1 = new Konva.Rect({
x: 200,
y: 200,
width: 100,
height: 50,
fill: "#00D2FF",
draggable: true,
rotation: 0,
name: "rect"
});
// convert degree to rad
const degToRad = (deg: number) => deg * (Math.PI / 180);
// here's the code i use to rotate it around its center (from https://konvajs.org/docs/posts/Position_vs_Offset.html)
const rotateAroundCenter = (node: Rect, rotation: number) => {
const topLeft = {
x: -node.width() / 2,
y: -node.height() / 2
};
console.log(`current X: ${node.x()}, current Y: ${node.y()},`)
const currentRotatePoint = rotatePoint(topLeft, degToRad(node.rotation()));
const afterRotatePoint = rotatePoint(topLeft, degToRad(rotation));
const dx = afterRotatePoint.x - currentRotatePoint.x;
const dy = afterRotatePoint.y - currentRotatePoint.y;
node.rotation(rotation);
node.x(node.x() + dx);
node.y(node.y() + dy);
layer.draw();
console.log(`the actual position x: ${node.x()}, y: ${node.y()}`);
};
// the code that i expected to give me the corner point
const computeCornerPoint = (r:Rect) => {
// for now we want to compute top left corner point(as it's the easiest corner to get)
let corner = {
x: r.x(),
y: r.y()
};
// the coordinate of rectangle's center (in stage coordinate)
const cx = r.x() + r.width() / 2;
const cy = r.y();
// sine and cosine of the rectangle's rotation
const s = Math.sin(degToRad(r.rotation()));
const c = Math.cos(degToRad(r.rotation()));
// rotate the corner point
let xnew = c * (corner.x - cx) - s * (corner.y - cy) + cx;
let ynew = s * (corner.x - cx) + c * (corner.y - cy) + cy;
console.log(`based on this function calculation: xnew : ${xnew}, ynew: ${ynew}`);
return [xnew, ynew];
}
根据上面的代码,如果初始旋转为0,我将矩形顺时针旋转30度, 那么实际位置将与来自 computeCornerPoint 的值相同,即 (219, 178),如果我再次将其顺时针旋转 30 度,则实际位置将是 (246, 169),而来自 computeCornerPoint 的值将是 (275 , 175)。
【问题讨论】:
-
您好 - 如果我的答案是正确的,请您点击勾号将其标记为正确答案。标记正确或最有帮助的答案有助于其他人判断其相关性并将积分奖励给回答者。谢谢。
标签: javascript rotation rectangles konvajs