0
votes

I'm having a brain-freeze trying to calculate the original coordinates of the top, left corner of a rectangle before it was rotated.

Given that I know rectangle was rotated n degrees/radians, and I know the new x and y coordinates, how would I calculate the x and y (? and ?) coordinates using trigonometry in JavaScript? I also know the width and height of the rectangle. The axis of the rotation is central to the rectangle.

example problem

The rotated rectangle is in blue, the original is in green.

2

2 Answers

1
votes

you have to counter-rotate it around the pivot. (center of the rect)

//utils
function nr(v){ return +v || 0 }

class Point{
    constructor(x,y){
        this.x = nr(x);
        this.y = nr(y);
    }

    add(pt){
        var a = this, b = Point.from(pt);
        return new Point(a.x + b.x, a.y + b.y);
    }

    subtract(pt){
        var a = this, b = Point.from(pt);
        return new Point(a.x - b.x, a.y - b.y);
    }

    rotate(radians, pivot){
        if(pivot){
            return this.subtract(pivot).rotate(radians).add(pivot);             
        }

        var r = nr(radians), c = Math.cos(r), s = Math.sin(r);
        return new Point(
            this.x * c - this.y * s,
            this.x * s + this.x * c
        );
        //return delta.matrixTransform( c, s, -s, c );
    }

    matrixTransform(a, b, c, d, tx, ty){
        return new Point(
            this.x * nr(a) + this.y * nr(c) + nr(tx),
            this.x * nr(b) + this.y * nr(d) + nr(ty)
        )
    }

    static from(pt){
        if(pt instanceof Point) return pt;
        return new Point(pt && pt.x, pt && pt.y);
    }
}

and the computation:

var RAD = Math.PI/180, DEG = 180/Math.PI;

var knownPoint = new Point(100, 100);
var angle = 30*RAD;

var unrotatedRect = { width: 150, height: 100 };
//the pivot to (counter-)rotate your known point
//if you know this point, you don't have to compute it
var pivot = new Point(unrotatedRect.width/2, unrotatedRect.height/2)
    .rotate(angle)
    .add(knownPoint);

console.log(knownPoint.rotate(-angle, pivot));
0
votes

The original X is exactly as far from the axis as the transposed ("rotated") Y is, and vice versa, the original Y is as far as the transposed X is from the axis.

So:

origX = axisX - (axisY - transY)
origY = axisY - (axisX - transX)