Programmatically rotate shapes using coordinates

2019-08-07 14:34发布

If I have some shapes defined using arrays of coordinates e.g.

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

and edges defined using:

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

to make a square.

How do I programmatically tell the shape to rotate *at the center against an angle of 0->359 in javascript?

*Or better yet, is there a function which allows me to choose the center of rotation?

** Currently, I've managed to get the shape to circle the canvas using :

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条回答
SAY GOODBYE
3楼-- · 2019-08-07 15:02

Here you go, rotates point x, y around point centerx, centery by degrees degrees. Returns floating values, round if you need to.

To rotate a shape, rotate all the points. Calculate the center if you need to, this does not do it.

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];
}
查看更多
小情绪 Triste *
4楼-- · 2019-08-07 15:03

You could use a formular for rotating the point around the origin.

function rotate(array, angle) {
    return array.map(function (p) {
        function r2d(a) { return a * Math.PI / 180; }
        return [
            Math.cos(r2d(angle)) * p[0] - Math.sin(r2d(angle)) * p[1],
            Math.sin(r2d(angle)) * p[0] - Math.cos(r2d(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; }

查看更多
登录 后发表回答