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

问题描述 投票:0回答:3

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

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

和边缘定义使用:

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

做一个正方形。

如何以编程方式告诉形状在 javascript 中以 0->359 的角度在中心旋转?

*或者更好的是,有没有可以让我选择旋转中心的功能?

** 目前,我已经成功地使用 :

获得了环绕画布的形状
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 
javascript canvas rotation shapes
3个回答
8
投票

在这里,将点

x, y
围绕点
centerx, centery
旋转
degrees
度。返回浮动值,如果需要则四舍五入。

要旋转形状,请旋转所有点。如果需要,请计算中心,这不会这样做。

Desmos链接

x
作为
a
y
作为
b
centerx
作为
p
centery
作为
q
,以及
degrees
作为
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];
}

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; }


© www.soinside.com 2019 - 2024. All rights reserved.