代码之家  ›  专栏  ›  技术社区  ›  Loveen Dyall

使用坐标以编程方式旋转形状

  •  1
  • Loveen Dyall  · 技术社区  · 7 年前

    如果我有一些使用坐标数组定义的形状,例如。

    [[-30, -30], [-30, 30], [30, 30], [30, -30]]
    

    [[0,1],[0,3],[1,2],[2,3]]
    

    做一个正方形。

    如何通过编程告诉形状以0->的角度在中心旋转*;359在javascript中?

    *或者更好的是,有没有一个函数可以让我选择旋转的中心?

    目前,我已成功使用以下工具使形状环绕画布:

    var x_rotate = Math.sin(angle * Math.PI /180);
    var y_rotate = Math.cos(angle * Math.PI /180);
    
    // for each coordinate
    //add x_rotate and y_rotate if coordinate > 0 or subtract if coordinate < 0 
    
    3 回复  |  直到 7 年前
        1
  •  7
  •   Oliver Ni    7 年前

    给你,旋转点 x, y 围绕点 centerx, centery degrees

    Desmos link with x as a , y as b , centerx as p , centery as q , and degrees as s

    function rotatePoint(x, y, centerx, centery, degrees) {
        var newx = (x - centerx) * Math.cos(degrees * Math.PI / 180) - (y - centery) * Math.sin(degrees * math.PI / 180) + centerx;
        var newy = (x - centerx) * Math.sin(degrees * Math.PI / 180) + (y - centery) * Math.cos(degrees * math.PI / 180) + centery;
        return [newx, newy];
    }
    
        2
  •  3
  •   Nina Scholz    3 年前

    你可以用一个 formular 用于围绕原点旋转点。

    function rotate(array, angle) {
        return array.map(function (p) {
            function d2r(a) { return a * Math.PI / 180; }
            return [
                Math.cos(d2r(angle)) * p[0] - Math.sin(d2r(angle)) * p[1],
                Math.sin(d2r(angle)) * p[0] - Math.cos(d2r(angle)) * p[1],
            ];
        });
    }
    console.log(rotate([[-30, -30], [-30, 30], [30, 30], [30, -30]], 45));
    console.log(rotate([[-30, -30], [-30, 30], [30, 30], [30, -30]], 90));
    .as-console-wrapper { max-height: 100% !important; top: 0; }