当你在div上设置旋转弧度/角度后,如何计算其左上角、左下角、右上角和右下角的像素位置?
举个例子会更好理解。
当你在div上设置旋转弧度/角度后,如何计算其左上角、左下角、右上角和右下角的像素位置?
举个例子会更好理解。
| cos(theta) -sin(theta) |
| sin(theta) cos(theta) |
例如:
x' = a * cos(theta) - b * sin(theta)
y' = a * sin(theta) + b * cos(theta)
NB:上述内容是针对笛卡尔坐标系的 - 根据需要反转 theta
项,以适用于DOM坐标系,其中y
轴向下运行。
我对这里的答案感到困惑。被贬低的答案肯定是错误的,但我也对另一个答案感到困惑,因为它是一个非常好但非常纯粹的提示。那里的例子对于通常的Web开发人员来说仍然非常理论化。所以我结合了两个答案,并制作了一个可行的版本贴在下面。所以,对于那些也在寻找工作的JavaScript解决方案的人,这里是:
function getPixelsByAngle(x, y, width, height, angle) {
var radians = angle * Math.PI / 180;
return [
//upper left
[x + width/2 + width/-2 * Math.cos(radians) - height/-2 * Math.sin(radians), y + height/2 + width/-2 * Math.sin(radians) + height/-2 * Math.cos(radians)],
//upper right
[x + width/2 + width/2 * Math.cos(radians) - height/-2 * Math.sin(radians), y + height/2 + width/2 * Math.sin(radians) + height/-2 * Math.cos(radians)],
//bottom right
[x + width/2 + width/2 * Math.cos(radians) - height/2 * Math.sin(radians), y + height/2 + width/2 * Math.sin(radians) + height/2 * Math.cos(radians)],
//bottom left
[x + width/2 + width/-2 * Math.cos(radians) - height/2 * Math.sin(radians), y + height/2 + width/-2 * Math.sin(radians) + height/2 * Math.cos(radians)],
];
}
这解决了我在旋转后计算新像素位置的问题。我创建了一个函数,可以传入x/y位置、div的一半宽度/高度和新的旋转角度。
function getPixelsByAngle(x,y,halfWidth,halfHeight,angle){
var bounds = [
//upper left
[x + (halfWidth) * Math.cos(angle) - (halfHeight) * Math.sin(angle) + halfWidth, y + (halfHeight) * Math.cos(angle) + (halfWidth) * Math.sin(angle) + halfHeight],
//upper right
[x - (halfWidth) * Math.cos(angle) - (halfHeight) * Math.sin(angle) + halfWidth, y + (halfHeight) * Math.cos(angle) - (halfWidth) * Math.sin(angle) + halfHeight],
//bottom right
[x - (halfWidth) * Math.cos(angle) + (halfHeight) * Math.sin(angle) + halfWidth, y - (halfHeight) * Math.cos(angle) - (halfWidth) * Math.sin(angle) + halfHeight],
//bottom left
[x + (halfWidth) * Math.cos(angle) + (halfHeight) * Math.sin(angle) + halfWidth, y - (halfHeight) * Math.cos(angle) + (halfWidth) * Math.sin(angle) + halfHeight]
];
return bounds;
}