Reputation: 957
I have a canvas which I draw an image onto. The image can be rotated to a certain amount of degrees before being drawn (EG: 30).
I need to draw a box to contain the drawn image; this would be easy but the width and height change depending on the angle the image is rotated to.
I have seen some very similar questions here, but I couldn't implement the answers into my code because they are either written in another language like ActionScript or they are rotating a div or other element not within a canvas. I haven't been able to work out the main math behind it.
I have created a JSFiddle for you to adapt:
I have created two functions in this JSFiddle:
drawImageToCanvasRotated(URL, X, Y, Angle);
drawRectangle(X, Y, Width, Height);
You should note that the position values are for the center of the image / rectangle.
Thanks.
Upvotes: 1
Views: 2445
Reputation: 154958
You rotate the image, so the new width becomes a combination of:
An analogous calculation applies for the new height. http://jsfiddle.net/ZY7Ux/1/
var a = Width * Math.cos(Angle);
var b = Height * Math.sin(Angle);
var c = a + b;
var p = Width * Math.sin(Angle);
var q = Height * Math.cos(Angle);
var r = p + q;
context.strokeRect(
X - c / 2,
Y - r / 2,
c,
r
);
Upvotes: 1