I have a html5 canvas. I want to draw/rotate the image in the canvas and image size does not change.I set width/height of canvas base on size of image.I have a problem to r
There are two issues you are facing:
To properly size your canvas you can use maximum boundary of the rotated rectangle. To find this boundary you can do one of two things:
If you only need to rotate per 90 degrees:
var length = Math.max(img.width, img.height);
If you want to use free angle:
var length = Math.sqrt(img.width * img.width + img.height * img.height);
Then use one of these results to set the size of the canvas:
canvas.width = canvas.height = length; /// both has same length
Next thing is to properly draw in the image. After rotation you need to translate back as the image is always drawn from its upper left corner:
var pivot = length * 0.5;
ctx.save();
ctx.translate(pivot, pivot);
ctx.rotate(degrees * Math.PI / 180);
ctx.drawImage(image, -image.width * 0.5, -image.height * 0.5);
ctx.restore();
It's important you use the pivot of the image to offset it back as the image will here be of a different size than canvas.
The result from this LIVE DEMO here:
