我在矩形中有一个点,我需要旋转任意度数并找到该点的x y。我怎么能用javascript做到这一点。
在x之下,y将是1,3,在我将90传递给方法后,它将返回3,1。
|-------------|
| * |
| |
| |
|-------------|
_____
| *|
| |
| |
| |
| |
_____
|-------------|
| |
| |
| *|
|-------------|
_____
| |
| |
| |
| |
|* |
_____
基本上我正在寻找这种方法的胆量
function Rotate(pointX,pointY,rectWidth,rectHeight,angle){
/*magic*/
return {newX:x,newY:y};
}
答案 0 :(得分:9)
这应该这样做:
function Rotate(pointX, pointY, rectWidth, rectHeight, angle) {
// convert angle to radians
angle = angle * Math.PI / 180.0
// calculate center of rectangle
var centerX = rectWidth / 2.0;
var centerY = rectHeight / 2.0;
// get coordinates relative to center
var dx = pointX - centerX;
var dy = pointY - centerY;
// calculate angle and distance
var a = Math.atan2(dy, dx);
var dist = Math.sqrt(dx * dx + dy * dy);
// calculate new angle
var a2 = a + angle;
// calculate new coordinates
var dx2 = Math.cos(a2) * dist;
var dy2 = Math.sin(a2) * dist;
// return coordinates relative to top left corner
return { newX: dx2 + centerX, newY: dy2 + centerY };
}
答案 1 :(得分:2)
newX = Math.cos(angle) * pointX - Math.sin(angle) * pointY;
newY = Math.sin(angle) * pointX + Math.cos(angle) * pointY;
确保指定相对于旋转原点的坐标!
(尚未完全检查语法,但数学基于旋转矩阵)