const ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(50, 50, 50, 50)
/**
*
* @returns {[number, number]} (x3, y3)
*/
function f(x1, y1, x2, y2, degrees) {
const rad = degrees * Math.PI / 180;
return [
(x2 - x1) * Math.cos(rad) + x1 - (y2 - y1) * Math.sin(rad),
(x2 - x1) * Math.sin(rad) + y1 + (y2 - y1) * Math.cos(rad)
]
}
ctx.fillStyle = "red";
const centre = 75;
/*
* The centre of the square is at (75, 75)
* The corner points are at:
* (50, 50)
* (100, 50)
* (100, 100)
* (50, 100)
*/
ctx.beginPath();
let [newX, newY] = f(centre, centre, 50, 50, 22.5);
ctx.moveTo(newX, newY);
[newX, newY] = f(centre, centre, 100, 50, 22.5);
ctx.lineTo(newX, newY);
[newX, newY] = f(centre, centre, 100, 100, 22.5);
ctx.lineTo(newX, newY);
[newX, newY] = f(centre, centre, 50, 100, 22.5);
ctx.lineTo(newX, newY);
[newX, newY] = f(centre, centre, 50, 50, 22.5);
ctx.lineTo(newX, newY);
ctx.fill();
<canvas width=200 height=200 style="background:gray"></canvas>