获取鼠标相对于旋转图像中心的位置

Getting mouse position relative to center of rotated image

我正在尝试编写一些代码,允许用户在 canvas 周围任意拖动图像、调整图像大小并使用鼠标旋转图像。我的三角函数有点问题。

所有兴趣点都相对于图像的中心。在下图中,鼠标位于绝对位置 850, 400(相对于 canvas' 左上角)。由于没有旋转我可以很容易地找出鼠标在相对位置 250, 0 (相对于图像的中心)。

我把图片旋转270°,鼠标放在原位置后,绝对值是600, 150。虽然相对位置与旋转前完全相同 (250, 0).

给定图像中心点的绝对坐标、旋转和鼠标的绝对位置,如何确定鼠标相对于图像中心的变换、旋转坐标?

我已经尝试了很多事情并试图从类似的 Whosebug 问题中改编答案。我目前的尝试使用 Matrix class 有人在 Gist 中发表。

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};
}

演示:https://plnkr.co/edit/T9XCfpZVlMWLMY67bOvW?p=preview

我在 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};
}