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

3
我正在尝试编写一些代码,允许用户任意拖动图像在画布上,调整图像大小,并使用鼠标旋转图像。 我在三角函数方面遇到了一些问题。
所有感兴趣的点都是相对于图像中心的。 在下面的插图中,鼠标位于绝对位置850, 400(相对于画布左上角)。由于没有旋转,我可以轻松计算出鼠标相对于图像中心的相对位置为250, 0

enter image description here

在将图像旋转270度并将鼠标放置在同一位置后,绝对位置为600,150。相对位置与旋转前完全相同(250,0)。

enter image description here

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

我已经尝试了很多方法,并尝试从类似的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};
}

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

1个回答

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接