Rotate rectangle around a point
14,929
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...
Author by
Anonymous
Updated on June 04, 2022Comments
-
Anonymous almost 2 years
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.
-
Max about 9 yearsCan you explain this? jsfiddle.net/bjhc34xk/7 Does this have anything to do with the approximation of PI, or perhaps floating point math errors?
-
brichins almost 8 yearsForked Felix's fiddle to include a slider for dynamic input to make it easier to experiment - jsfiddle.net/brichins/0ccdd362
-
brichins almost 8 years@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: jsfiddle.net/brichins/w2rxsbt4