8

How would I get 4 points rotated a certain degrees around a pointer to form a rectangle? I can rotate a point around a point, but I can't offset it to make a rectangle that isn't distorted.

Phrogz
  • 296,393
  • 112
  • 651
  • 745
Anonymous
  • 1,823
  • 7
  • 23
  • 29
  • 2
    have you tried to do it so far? some code? thanks – Trufa Dec 16 '10 at 22:26
  • 3
    Translate your four points so that you're treating the pointer as the center, do the rotation via the standard rotation matrix method, and then translate the points back. [Explanation here](http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm) – Michal Dec 16 '10 at 23:45
  • If I understood that I'd use it, but I need a solution in plain English or preferably JavaScript. – Anonymous Dec 17 '10 at 08:03

1 Answers1

41

If you can rotate a point around a point then it should be easy to rotate a rectangle - you just rotate 4 points.

Here is a js function to rotate a point around an origin:

function rotate_point(pointX, pointY, originX, originY, angle) {
    angle = angle * Math.PI / 180.0;
    return {
        x: Math.cos(angle) * (pointX-originX) - Math.sin(angle) * (pointY-originY) + originX,
        y: Math.sin(angle) * (pointX-originX) + Math.cos(angle) * (pointY-originY) + originY
    };
}

And then you can do this to each point. Here is an example: http://jsfiddle.net/dahousecat/4TtvU/

Change the angle and hit run to see the result...

Felix Eve
  • 3,811
  • 3
  • 40
  • 50
  • Can you explain this? jsfiddle.net/bjhc34xk/7 Does this have anything to do with the approximation of PI, or perhaps floating point math errors? – Max Apr 04 '15 at 23:52
  • 2
    Forked Felix's fiddle to include a slider for dynamic input to make it easier to experiment - https://jsfiddle.net/brichins/0ccdd362/ – brichins Jul 15 '16 at 18:05
  • 3
    @MaxMastalerz I'm sure you moved on from this by now, but your Fiddle is probably not doing what you thought. You are changing the X coordinate of your endpoint, in the middle of the calculation, then rotating the Y coordinate from that offset point instead of the center. Results in a cool golden spiral, but I think you meant to do this: https://jsfiddle.net/brichins/w2rxsbt4/ – brichins Jul 15 '16 at 18:15
  • Shouldn't it be `y: Math.cos(angle) * (pointX-originX) + Math.sin(angle) * (pointY-originY) + originY` instead of `y: Math.sin(angle) * (pointX-originX) + Math.cos(angle) * (pointY-originY) + originY`? – Victor Nov 22 '22 at 14:32
  • 1
    @Victor: Think about what happens when `angle = 0`, so `Math.sin(angle)` is `0` and `Math.cos(angle)` is `1`. The formula in the answer then reduces to `y: 0 * (pointX - originX) + 1 * (pointY - originY) + originY`, which is `pointY`, as expected (rotation by zero shouldn't change the point). Your suggested formula would end up giving `y: pointX - originX + originY` instead. – Mark Dickinson Nov 22 '22 at 17:20