我正在尝试编写一些代码,以使用户可以在画布上随意拖动图像,调整图像大小并使用鼠标旋转图像。我的三角学遇到了麻烦。
所有兴趣点均相对于图像中心。在下图中,鼠标位于 850、400 的绝对位置(相对于画布的左上角)。由于没有旋转,因此我可以很容易地发现鼠标处于相对位置 250,0 (相对于图像中心)。
将图像旋转270°并将鼠标放在同一位置后,绝对值为 600、150 。相对位置与旋转之前的位置完全相同( 250,0 )。
给出图像中心点的绝对坐标,旋转角度以及鼠标的绝对位置,如何确定鼠标相对于图像中心的旋转坐标? >
我已经尝试了很多事情,并尝试从类似的StackOverflow问题中改编答案。我目前的尝试使用某人在Gist中发布的Matrix类。
layerRelativePoint(x, y, layer){
var radians = layer.rotation * (Math.PI/180);
var matrix = new Matrix();
matrix.translate(-layer.x, -layer.y);
matrix.rotate(radians);
var [x, y] = matrix.transformPoint(x, y);
return {x, y};
}
答案 0 :(得分:0)
我在Math.se上找到了答案。
这是我想出的实现方式:
/**
* Translate a point's absolute coordinates to it's coordinates
* relative to a possibly rotated center point
* -------------------------------------------------------------
* @param {number} absPointX - The absolute x ordinate of the point to translate
* @param {number} absPointY - The absolute y ordinate of the point to translate
* @param {number} centerX - The absolute x ordinate of the center point of rotation
* @param {number} centerY - The absolute y ordinate of the center point of rotation
* @param {number} rotationDegrees - The angle of rotation in degrees
* @returns {x, y} - The translated point's coordinates
*/
function translatePoint(absPointX, absPointY, centerX, centerY, rotationDegrees=0) {
// Get coordinates relative to center point
absPointX -= centerX;
absPointY -= centerY;
// Convert degrees to radians
var radians = rotationDegrees * (Math.PI / 180);
// Translate rotation
var cos = Math.cos(radians);
var sin = Math.sin(radians);
var x = (absPointX * cos) + (absPointY * sin);
var y = (-absPointX * sin) + (absPointY * cos);
// Round to nearest hundredths place
x = Math.floor(x * 100) / 100;
y = Math.floor(y * 100) / 100;
return {x, y};
}