0

I want to rotate image but resize the canvas based on image's width and height. please see my code in JSFiddle. I am actually rotating an image based on canvas but my canvas has fixed height and width so the image is just rotating inside. all i want something like this. Please check my attached screenshot. green border is a canvas so if i rotate 90 degree then canvas should expand the height and show the entire image.

Can you please help?

HTML

<canvas id="canvas" ></canvas><br>
<button id="clockwise">Rotate right</button>

JavaScript

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var degrees=0;
var image=document.createElement("img");
image.onload=function(){
    ctx.drawImage(image,0,0,image.width,image.height);
}
image.src="http://www.ajaxblender.com/article-sources/images/plane-1.jpg";
$("#clockwise").click(function(){
   degrees+=90
   ctx.clearRect(0,0,canvas.width,canvas.height);
   ctx.save();
   ctx.translate(image.width/2,image.height/2);
   ctx.rotate(degrees*Math.PI/180);
   ctx.drawImage(image,0,0,image.width,image.height,-image.width/2,-image.height   /2,image.width,image.height);
   ctx.restore();
});

enter image description here

Syscall
  • 19,327
  • 10
  • 37
  • 52
orbnexus
  • 737
  • 1
  • 9
  • 38

1 Answers1

2

First initialize the canvas size when the image has loaded:

image.onload=function(){
    canvas.width = image.width;
    canvas.height = image.height;    
    ctx.drawImage(image,0,0);
}

Now you can use the angles as basis for the canvas size. If 0 or 180 degrees then use the same size as image, if not swap the dimensions:

 if (degrees >= 360) degrees = 0;

 if (degrees === 0 || degrees === 180) {
     canvas.width = image.width;
     canvas.height = image.height;
 }
 else {
     // swap
     canvas.width = image.height;
     canvas.height = image.width;
 }

There is no need to clear the canvas as changing the size will clear it (otherwise it would only be needed if the image contained a transparency channel).

You also want to rotate the image around the center of canvas (not a big issue here though).

Modified fiddle

Syscall
  • 19,327
  • 10
  • 37
  • 52
  • Thank you very much for the quick help. one more question. If i resize the image using Jquery UI so usually Jquery UI add the style="width,height" on the image then if i rotate image then it just rotates it based on the image original dimensions not the dimensions from resized image. Please see my **[updated JS fiddle](http://jsfiddle.net/6ZsCz/1137/)**. is it possible if i resize the image and then if i rotate the image then it just rotates based on the resized dimensions? – orbnexus Nov 06 '14 at 20:01
  • 1
    @mak I updated the fiddle here. add an id to the html image, read the w/h from it, set it on canvas and use it with drawImage, and you should be fine: http://jsfiddle.net/epistemex/bfwdqgm3/ If still unclear just open a new question. Hope this helps! –  Nov 07 '14 at 01:37