Home > Back-end >  How to calculate a bounding box for a rectangle rotated around its center?
How to calculate a bounding box for a rectangle rotated around its center?

Time:09-18

I am looking to calculate the bounding box of a rectangle rotated around its center. I have read enter image description here

CodePudding user response:

Size of bounding box (description here)

H = w * Abs(Sin(Fi))   h * Abs(Cos(Fi))
W = w * Abs(Cos(Fi))   h * Abs(Sin(Fi))

Having rXCenter, rYCenter, you can find get bounds coordinates

x0  = rXCenter - W/2
y0  = rYCenter - H/2

CodePudding user response:

It feels like you are over thinking this. Here I show how to draw three rectangles rotated around a center pointt I made blue.

const wrapper = document.getElementById('wrapper');
const canvas = document.getElementById('canvas');
const wCS = window.getComputedStyle(wrapper, null)
const pl = parseFloat(wCS.getPropertyValue('padding-left'));
const pt = parseFloat(wCS.getPropertyValue('padding-top'));
const pr = parseFloat(wCS.getPropertyValue('padding-right'));
const pb = parseFloat(wCS.getPropertyValue('padding-bottom'));
canvas.width = wrapper.clientWidth - pl - pr;
canvas.height = wrapper.clientHeight - pt - pb;

const ctx = canvas.getContext('2d');
// setup a rectangle
let cornerLeft = 70;
let cornerTop = 70;
let width = 180;
let height = 60;
let horizontalCenter = cornerTop   (width / 2);
let verticalCenter = cornerTop   (height / 2);
let centerPoint = {
  horz: horizontalCenter,
  vert: verticalCenter
};
let colorBlue = '#0000FF';
let colorLime = '#40FF40';
let colorPurple = '#4040FF';
let colorOrange = '#FFA500';

ctx.fillStyle = colorBlue;
ctx.fillRect(centerPoint.horz, centerPoint.vert, 8, 8); // fill in the pixels at center point

ctx.strokeStyle = colorPurple;
ctx.strokeRect(cornerTop, cornerLeft, width, height); // horizontal purple box

ctx.strokeStyle = colorOrange;
ctx.translate(centerPoint.horz, centerPoint.vert); // center point note positive
ctx.rotate(Math.PI / 2); // vertical
ctx.translate(-centerPoint.horz, -centerPoint.vert); // center point - note negative
ctx.strokeRect(cornerTop, cornerLeft, width, height); // vertical orange box

ctx.strokeStyle = colorLime;
ctx.translate(-centerPoint.horz * (1.375), -centerPoint.vert * (0.5)); // center point - note negative
ctx.rotate((Math.PI / 2) / -2); //back left by 45 deg left
ctx.translate(centerPoint.horz * (.025), centerPoint.vert * (2.75)); // center point note positive
ctx.strokeRect(cornerTop, cornerLeft, width, height);
#wrapper {
  width: 400px;
  height: 400px;
  padding: 2rem;
  border: 1px solid blue;
}

#canvas {
  border: 1px solid orange;
}
<div id="wrapper"><canvas id="canvas"></canvas></div>

  • Related