How to rotate a point around an origin with javascript

Posted on: November 3rd, 2012 by admin 1 Comment

Whilst this is quite simple I had trouble finding a easy to understand tutorial on this so put this up here for reference.

Step 1 – Convert the angle you are rotating to from degrees to radians.

To do this we just times the angle by PI and divide by 180.

1
angle = angle * Math.PI / 180.0;

Step 2 – Calculate new X and new Y

The formular for this is:

1
2
3
x = Math.cos(angle) * (pointX-originX) - Math.sin(angle) * (pointY-originY) + originX;
y = Math.sin(angle) * (pointX-originX) + Math.cos(angle) * (pointY-originY) + originY;
}

Step 3 – The whole function

So to put the whole thing together into a function would look like this:

1
2
3
4
5
6
7
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
	};
}
Tags: , ,