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+=10;
drawRotated(currentDegrees);
});
$("#counterclockwise").click(function(){
currentDegrees-=10;
drawRotated(currentDegrees);
});
function drawRotated(degrees){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.translate(canvas.width/2,canvas.height/2);
var boundingRectBefore = image.getBoundingClientRect();
ctx.rotate(degrees*Math.PI/180);
var boundingRectAfter = image.getBoundingClientRect();
console.log(boundingRectBefore, boundingRectAfter);
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();
}
function straightenChange(e) {
//this._isStraighten = !0, e && (this._isDrawStraighten = !0);
var t = {
x: this._currentImg.width / 2,
y: this._currentImg.height / 2
},
n = o.convertPointByAngle({
x: 0,
y: 0
}, t, Math.abs(e));
t.x < t.y ? this._rotateScale = 1 - n.x / t.x : this._rotateScale = 1 + n.y / t.y,...