Search code examples
javascriptjqueryhtml5-canvasimage-rotation

Image rotate - resize canvas based on image height and width


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


Solution

  • 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