Canvas Rotate and Fit

by Vijay Gujar

HTML

<canvas id="canvas" width=350 height=350></canvas><br>
<button id="clockwise">Clock Wise</button>
<button id="counterclockwise">Counter CW</button>

CSS

body{ background-color: white; }
canvas{border:1px solid green;}

JavaScript

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");

var currentDegrees=0;

var image=document.createElement("img");
image.onload=function(){
						var wrh = image.width / image.height;
            var newWidth = canvas.width;
            var newHeight = newWidth / wrh;
            if (newHeight > canvas.height) {
                newHeight = canvas.height;
                newWidth = newHeight * wrh;
            }
    ctx.drawImage(image,0,0,newWidth,newHeight);
}
image.src="http://i.imgur.com/8rmMZI3.jpg";

$("#clockwise").click(function(){ 
    currentDegrees+=90;
    drawRotated(currentDegrees);
});

$("#counterclockwise").click(function(){ 
    currentDegrees-=90;
    drawRotated(currentDegrees);
});

function drawRotated(degrees){
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.save();
    ctx.translate(canvas.width/2,canvas.height/2);
    ctx.rotate(degrees*Math.PI/180);
    	var wrh = image.width / image.height;
            var newWidth = canvas.width;
            var newHeight = newWidth / wrh;
            if (newHeight > canvas.height) {
                newHeight = canvas.height;
                newWidth = newHeight * wrh;
            }
    ctx.drawImage(image,-canvas.width/2,-canvas.height/2,newWidth,newHeight);
   
    ctx.restore();
}