Rotate point in rectangle

夙愿已清 提交于 2019-11-30 07:12:27

This should do it:

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 };
}
newX = Math.cos(angle) * pointX - Math.sin(angle) * pointY;
newY = Math.sin(angle) * pointX + Math.cos(angle) * pointY;

Make sure to specify the coordinates relative to the rotation origin!

(Haven't checked the syntax exactly, but the math is based on a rotation matrix)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!