javascriptcoordinates

Calculate point coords relative to a rotated DIV


I have a rotated DIV within a non-rotated DIV and I'm trying to work out the cursor position on the outer DIV in relation to the rotated DIV. I guess I need the position as though the coordinate system has been rotated to match the angle of the rotated div.

Following is an example of what I need:

rotated DIV within a DIV

I know or can easily get:

I don't know how to get, but need, x2 and y2.


Solution

  • I ignore whether you can access that information using built-in tools, so here is a possible answer that centres on the maths of the problem.

    What you're doing is basically an affine transformation, specifically the composition of a translation and a rotation:

    Transformation equation.

    Where the rotation matrix is:

    Rotation matrix.

    ; and the translation vector is:

    Translation vector.

    So, in fine, the coordinates in the new system should be:

    let x2 = x1*Math.cos(a) + Math.sin(a) * (-y1 + w2*Math.sin(a));
    let y2 = y1*Math.cos(a) + Math.sin(a) * (+x1 - w2*Math.cos(a));
    

    EDIT - The previous solution deals with the original posted problem; to tackle the "new" modified version - as described by the OP in the comments -, there are two possibilities:

    1. either to simply apply to the above result the transformation (x, y) --> (x, h2-y) (this is the easy way);
    2. or to re-formalise the problem from scratch. We'll now do this for didactic reasons.

    In this second scenario, apart from the aforementioned rotation and translation, the affine transformation includes a reflection about the x axis, and an additional translation:

    Transformation equation.

    ; where the rotation matrix is still:

    Rotation matrix.

    ; the reflection can be written:

    Reflection matrix.

    ; the first translation, as before, is:

    First translation vector.

    ; and, finally, the second translation vector:

    Second translation vector.

    Inverting the system, the final result is:

    let x2 = +x1*Math.cos(a) + Math.sin(a) * (-y1 + w2*Math.sin(a));
    let y2 = -y1*Math.cos(a) + Math.sin(a) * (-x1 + w2*Math.cos(a)) + h2;