How to calculate rotation in 2D in Javascript

function rotate(cx, cy, x, y, angle) {
    var radians = (Math.PI / 180) * angle,
        cos = Math.cos(radians),
        sin = Math.sin(radians),
        nx = (cos * (x - cx)) + (sin * (y - cy)) + cx,
        ny = (cos * (y - cy)) - (sin * (x - cx)) + cy;
    return [nx, ny];
}

The first two parameters are the X and Y coordinates of the central point (the origin around which the second point will be rotated). The next two parameters are the coordinates of the point that we’ll be rotating. The last parameter is the angle, in degrees.

As an example, we’ll take the point (2, 1) and rotate it around the point (1, 1) by 90 degrees clockwise.

rotate(1, 1, 2, 1, 90);
// > [1, 0]

Three notes about this function:

  1. For clockwise rotation, the last parameter angle should be positive. For counterclockwise rotation (like in the diagram you provided), it should be negative.

  2. Note that even if you provide arguments that should yield a point whose coordinates are whole numbers — i.e. rotating the point (5, 0) by 90 degrees about the origin (0, 0), which should yield (0, -5) — JavaScript’s rounding behavior means that either coordinate could still be a value that’s frustratingly close to the expected whole number, but is still a float. For example:

    rotate(0, 0, 5, 0, 90);
    // > [3.061616997868383e-16, -5]
    

    For this reason, both elements of the resulting array should be expected as a float. You can convert them to integers using Math.round(), Math.ceil(), or Math.floor() as needed.

  3. Finally, note that this function assumes a Cartesian coordinate system, meaning that values on the Y axis become higher as you go “up” in the coordinate plane. In HTML / CSS, the Y axis is inverted — values on the Y axis become higher as you move down the page.

Leave a Comment