您可以使用同一侧的任何坐标对来计算旋转角度。请注意,数学角度通常假设 +ve X 轴长度为 0,并通过逆时针旋转而增加(因此沿 +ve Y 轴为 90°,-ve X 轴为 180°,依此类推)。
此外,JavaScript 三角函数返回的值以弧度表示,在用于 CSS 转换之前必须将其转换为度数。
如果形状旋转不超过 90°,则情况相当简单,您可以使用直角三角形的切线比:
tan(angle) = length of opposite side / length of adjacent side
对于 OP,最好使用的角是 1 和 4,以便旋转保持在第一象限并顺时针(根据CSS3 规范草案 http://www.w3.org/TR/css3-transforms/#two-d-transform-functions)。用 JavaScript 术语来说:
var rotationRadians = Math.atan((x1 - x4) / (y1 - y4));
转换为度数:
var RAD2DEG = 180 / Math.PI;
var rotationDegrees = rotationRadians * RAD2DEG;
如果旋转超过90°,则需要调整角度。例如如果角度大于 90° 但小于 180°,您将从上面得到 -ve 结果,需要添加 180°:
rotationDegrees += 180;
另外,如果您使用页面尺寸,则 y 坐标沿着页面向下增加,这与正常的数学意义相反,因此您需要反转y1 - y4
在上面。
Edit
基于 OP 中点的方向,以下是返回矩形中心和顺时针旋转度数的通用函数。这就是您所需要的,不过如果您愿意,您可以自己将角旋转到“水平”。您可以应用三角函数来计算新的角点或仅进行一些平均值(类似于 Ian 的答案)。
/** General case solution for a rectangle
*
* Given coordinages of [x1, y1, x2, y2, x3, y3, x4, y4]
* where the corners are:
* top left : x1, y1
* top right : x2, y2
* bottom right: x3, y3
* bottom left : x4, y4
*
* The centre is the average top left and bottom right coords:
* center: (x1 + x3) / 2 and (y1 + y3) / 2
*
* Clockwise rotation: Math.atan((x1 - x4)/(y1 - y4)) with
* adjustment for the quadrant the angle is in.
*
* Note that if using page coordinates, y is +ve down the page which
* is the reverse of the mathematic sense so y page coordinages
* should be multiplied by -1 before being given to the function.
* (e.g. a page y of 400 should be -400).
*
* @see https://stackoverflow.com/a/13003782/938822
*/
function getRotation(coords) {
// Get center as average of top left and bottom right
var center = [(coords[0] + coords[4]) / 2,
(coords[1] + coords[5]) / 2];
// Get differences top left minus bottom left
var diffs = [coords[0] - coords[6], coords[1] - coords[7]];
// Get rotation in degrees
var rotation = Math.atan(diffs[0]/diffs[1]) * 180 / Math.PI;
// Adjust for 2nd & 3rd quadrants, i.e. diff y is -ve.
if (diffs[1] < 0) {
rotation += 180;
// Adjust for 4th quadrant
// i.e. diff x is -ve, diff y is +ve
} else if (diffs[0] < 0) {
rotation += 360;
}
// return array of [[centerX, centerY], rotation];
return [center, rotation];
}