【问题标题】:Having trouble of rotated square when getting its corners获取角时遇到旋转正方形的麻烦
【发布时间】:2014-05-29 15:41:24
【问题描述】:

在获取旋转正方形的角时,任何人都可以知道我的公式有什么问题吗?当我将正方形从 1 度旋转到 10 度时似乎是正确的,但是当你给它 10 度以上的旋转时,我得到了错误的角位置。

这段代码来自我的 Square 类的 getCorners() 方法:

var hx = 0,
    hy = 0;

hx = hy = this.size / 2;

var cos = Math.cos(this.rotation * Math.PI / 180),
    sin = Math.sin(this.rotation * Math.PI / 180);                      

var corners = {
      a: { x: this.x - hx, y: this.y - hy },
      b: { x: this.x + hx, y: this.y - hy },
      c: { x: this.x + hx, y: this.y + hy },
      d: { x: this.x - hx, y: this.y + hy }
};

var tl = corners.a,
    tr = corners.b,
    br = corners.c,
    bl = corners.d;

corners.a.x = (tl.x - this.x) * cos - (tl.y - this.y) * sin + this.x;
corners.a.y = (tl.x - this.x) * sin + (tl.y - this.y) * cos + this.y;                                           

corners.b.x = (tr.x - this.x) * cos - (tr.y - this.y) * sin + this.x;
corners.b.y = (tr.x - this.x) * sin + (tr.y - this.y) * cos + this.y;                                                                   

corners.c.x = (br.x - this.x) * cos - (br.y - this.y) * sin + this.x;
corners.c.y = (br.x - this.x) * sin + (br.y - this.y) * cos + this.y;                                                                                           

corners.d.x = (bl.x - this.x) * cos - (bl.y - this.y) * sin + this.x;
corners.d.y = (bl.x - this.x) * sin + (bl.y - this.y) * cos + this.y;

完整源代码和运行程序的链接:http://jsfiddle.net/css3guy/8B2eT/

【问题讨论】:

    标签: html math canvas trigonometry


    【解决方案1】:

    您的公式(旋转矩阵)是正确的,但您使用的是参考值,这意味着您正在更新计算的第一部分中的值,然后其余计算使用该新值而不是您想要的值。

    解决此问题的一种方法是改为以这种方式定义您的对象(仅显示一个角):

    // clone the values instead of referencing them
    var tl = {x:corners.a.x, y:corners.a.y},
        ...
    
    // now you have a copy to work with here instead of accumulated updates
    corners.a.x = (tl.x - this.x) * cos - (tl.y - this.y) * sin + this.x;
    corners.a.y = (tl.x - this.x) * sin + (tl.y - this.y) * cos + this.y;
    

    Modified fiddle (only one corner fixed)

    我强烈建议重构并改用通用的旋转/平移函数。

    【讨论】:

    • 嗨,你是什么意思而不是普通的旋转/平移功能?抱歉,我对此很陌生。无论如何,谢谢你解决了我的问题。
    • @css3 很高兴它成功了。我的意思是一个独立于角落进行数学运算的函数。只需将它传递一个角/旋转/翻译,它就会吐出一个新的。通过这种方式,您可以在一个地方维护代码、减少代码、提高速度、使其更具可读性等。只是一个提示。
    猜你喜欢
    • 2020-11-02
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多