Calculate 2D rotation javascript HTML canvas

Solution 1:

Here is how I would do it:

function getRectangeCoordinates(x, y, width, height, angle) {
  let points = [ [x, y] ]
  let radians = (Math.PI / 180) * angle;
  for (let i = 0; i < 3; i++) {
    x += Math.cos(radians) * ((i == 1) ? height : width);
    y += Math.sin(radians) * ((i == 1) ? height : width);
    points.push([x, y])
    radians += Math.PI / 2
  }
  return points
}

let canvas = document.createElement("canvas");
canvas.width = canvas.height = 140
let ctx = canvas.getContext('2d');
document.body.appendChild(canvas);

function draw(coords, radius) {
  for (let i = 0; i < 4; i++) {
    ctx.beginPath();
    ctx.arc(coords[i][0], coords[i][1], radius, 0, 8);
    ctx.moveTo(coords[i][0], coords[i][1]);
    let next = (i + 1) % 4
    ctx.lineTo(coords[next][0], coords[next][1]);
    ctx.stroke();
  }
}

let coords = getRectangeCoordinates(20, 10, 120, 40, 15)
console.log(JSON.stringify(coords))
draw(coords, 3)

ctx.strokeStyle = "red";
coords = getRectangeCoordinates(60, 40, 40, 50, 65)
draw(coords, 5)

ctx.strokeStyle = "blue";
coords = getRectangeCoordinates(120, 3, 20, 20, 45)
draw(coords, 2)

In the getRectangeCoordinates I'm returning all corners of a rectangle and the paraments of the function are the top left corner (x, y) the height and width of the rectangle and last the angle.

I'm drawing a few rectangles with different shapes and angles to show how it looks like


The calculations in the function are simple trigonometry here is a visual representation that could help you remember it the next time you need it: