Calculate the bounding box's X, Y, Height and Width of a rotated element via JavaScript Calculate the bounding box's X, Y, Height and Width of a rotated element via JavaScript javascript javascript

Calculate the bounding box's X, Y, Height and Width of a rotated element via JavaScript


I know this is a bit late, but I've written a fiddle for exactly this problem, on an HTML5 canvas:

http://jsfiddle.net/oscarpalacious/ZdQKg/

I hope somebody finds it useful!

I'm actually not calculating your x,y for the upper left corner of the container. It's calculated as a result of the offset (code from the fiddle example):

this.w = Math.sin(this.angulo) * rotador.h + Math.cos(this.angulo) * rotador.w;this.h = Math.sin(this.angulo) * rotador.w + Math.cos(this.angulo) * rotador.h;// The offset on a canvas for the upper left corner (x, y) is// given by the first two parameters for the rect() method:contexto.rect(-(this.w/2), -(this.h/2), this.w, this.h);

Cheers


Have you tried using getBoundingClientRect() ?

This method returns an object with current values of "bottom, height, left, right, top, width" considering rotations


Turn the four corners into vectors from the center, rotate them, and get the new min/max width/height from them.

EDIT:

I see where you're having problems now. You're doing the calculations using the entire side when you need to be doing them with the offsets from the center of rotation. Yes, this results in four rotated points (which, strangely enough, is exactly as many points as you started with). Between them there will be one minimum X, one maximum X, one minimum Y, and one maximum Y. Those are your bounds.