javascript – 如何根据中心单元格旋转对象

前端之家收集整理的这篇文章主要介绍了javascript – 如何根据中心单元格旋转对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个网格,我在其中放置一个对象,我想围绕一个固定的单元格(cell3)旋转.该对象包含坐标,如:

  1. activeObject = {
  2. coords: {
  3. cell1: {
  4. x: 0,y: 0
  5. },cell2: {
  6. x: 1,y: 1
  7. },cell3: {
  8. x: 2,y: 2
  9. },cell4: {
  10. x: 2,y: 3
  11. },cell5: {
  12. x: 3,}
  13. }

输出

我想围绕cell3旋转这个对象,例如使用x:2,y:2,不使用某种(基本)三角函数对每个单元格位置进行硬编码.我意识到我必须检查每个细胞与细胞3的距离以及方向.但是我不知道如何进行计算,因为我对三角学不太了解.新的活动对象将是:

  1. activeObject = {
  2. coords: {
  3. cell1: {
  4. x: 4,cell2: {
  5. x: 4,cell4: {
  6. x: 1,cell5: {
  7. x: 1,}
  8. }

输出

enter image description here

最佳答案
一些基本的想法

>如果枢轴不是原点,则必须对变换进行一些修正.
>如果一个点位于(1,2),则围绕原点旋转

> 90°CW:变为(2,-1)
> 90°CCW:变为(-2,1)

>点(x,y)的结论

> 90°CW:成为(y,-x)
> 90°CCW:变为(-y,x)

>至少应用枢轴修正

一些数学被发现here.

  1. function Point(x,y) {
  2. this.x = x;
  3. this.y = y;
  4. }
  5. Point.prototype.rotateCW = function (c) {
  6. // x' = x cos phi + y sin phi \ formula with pivot at (0,0)
  7. // y' = -x sin phi + y cos phi /
  8. // phi = 90° insert phi
  9. // cos 90° = 0 sin 90° = 1 calculate cos and sin
  10. // x' = y \ formula with pivot at (0,0)
  11. // y' = -x /
  12. // x' = (cy - y) + cx \ formula with different pivot needs correction
  13. // y' = -(cx - x) + cy /
  14. // y' = -cx + x + cy /
  15. return new Point(
  16. c.x + c.y - this.y,c.y - c.x + this.x
  17. );
  18. }
  19. Point.prototype.rotateCCW = function (c) {
  20. // source: https://en.wikipedia.org/wiki/Rotation_(mathematics)#Two_dimensions
  21. // x' = x cos phi + y sin phi \ formula with pivot at (0,0)
  22. // y' = -x sin phi + y cos phi /
  23. // phi = -90°
  24. // cos -90° = 0 sin -90° = -1
  25. // x' = -y \ formula with pivot at (0,0)
  26. // y' = x /
  27. // x' = -(cy - y) + cx \ formula with different pivot needs correction
  28. // x' = -cy + y + cx /
  29. // y' = (cx - x) + cy /
  30. return new Point(
  31. c.x - c.y + this.y,c.y + c.x - this.x
  32. );
  33. }
  34. var activeObject = {
  35. coords: {
  36. cell1: new Point(0,0),cell2: new Point(1,1),cell3: new Point(2,cell4: new Point(2,3),cell5: new Point(3,}
  37. },pivot = new Point(2,rotated = { coords: {} };
  38. Object.keys(activeObject.coords).forEach(function (k) {
  39. rotated.coords[k] = activeObject.coords[k].rotateCW(pivot);
  40. });
  41. document.write('

猜你在找的JavaScript相关文章