Programmatically rotate shapes using coordinates

后端 未结 3 1171
时光说笑
时光说笑 2021-01-23 07:47

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

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

and edges defined using:

         


        
相关标签:
3条回答
  • 2021-01-23 08:01

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

    0 讨论(0)
  • 2021-01-23 08:11

    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];
    }
    
    0 讨论(0)
  • 2021-01-23 08:23

    use css transition and change transform by javascript

    https://www.w3schools.com/cssref/css3_pr_transform.asp

    https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions

    0 讨论(0)
提交回复
热议问题