Search code examples
javascriptrotationtrigonometrylimejs

javascript finding center of a rotated rectangle


Using Javascript and a js library (limeJS) I'm drawing a rectangle when user clicks at a point and then rectangle is being rotating and changing size (only width, height is static) until user release mouse button.

(hm cannot post image - need 10 reputation points - so here is image link http://d.pr/i/KsBQ )

Rectangle is being rotated by upper right corner (red dot in image) and size and rotation is being calculating based on mouse cursor (blue dot).

Finally when user release mouse button I want to find rectangle's center.

I'm able to do all that (find distance, rotation) and center but it seems that I'm doing something wrong with center when upper right corner (red dot) y is greater than mouse point (blue dot) y. What I'm doing is finding the down left corner and I have the upper left:

var BOX_HEIGHT = 20;
// pos: upper right rectangle's position (red dot), mpos: mouse position (blue dot), rotation: rectangle's rotatio
test.GetCenter = function(pos, mpos, rotation)
{
    var dpos = {}, ret = {}, rot = (Math.abs(rotation) + 90) ;
    // find down left corner
    dpos.x = BOX_HEIGHT * Math.cos(rot * Math.PI / 180) + mpos.x;
    dpos.y = BOX_HEIGHT * Math.sin(rot * Math.PI / 180) + mpos.y;

    ret.x = Math.abs((pos.x + dpos.x) / 2);
    ret.y = Math.abs((pos.y + dpos.y) / 2);
    return ret;
}

Solution

  • In the situation you describe when there is a problem, the roles of the two dots are reversed: you HAVE the lower one and want to find the upper. Add an if statement to detect this condition, and write a version of your code that recognizes this reversal.