user2559108
user2559108

Reputation:

HTML5 rotating canvas image

i want to allow users to rotate a canvas, while changing dimensions if they no longer fit after the rotation, here is a fiddle:

http://jsfiddle.net/6ZsCz/84/

I cant seem to figure out the x/y positions after the transform:

ctx.translate(canvas.width/2,canvas.height/2);

As you see, the image does rotate, but when it rotates left/right it goes off canvas, how can i compress the height to force it to stay in borders, here is an example of what i want to achive when it rotates.

enter image description here

EDIT:

since this question seems very popular, i am posting the solution here instead of JSFiddle

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var angleInDegrees=0;
var image=document.createElement("img");
image.onload=function(){
    ctx.drawImage(image,(canvas.width - image.width) / 2, (canvas.height - image.height) / 2,image.width, image.height);//ctx.drawImage(img, x, y, width, height)
}
image.src="http://www.farmvertical.com/wp-content/uploads/2007/10/vertical_farm_v2.jpg";
$("#clockwise").click(function(){ 
    angleInDegrees+=90;
    drawRotated(angleInDegrees);
});
$("#counterclockwise").click(function(){ 
    angleInDegrees-=90;
    drawRotated(angleInDegrees);
});
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);

    if(angleInDegrees%180==0){
        ctx.drawImage(image, -image.width/2,-image.height/2);
    }else{
        ctx.drawImage(image, -image.width/2,-canvas.width/2,image.width, canvas.width);
    }
    ctx.restore();
}

Upvotes: 2

Views: 1659

Answers (1)

Edward Lee
Edward Lee

Reputation: 951

Is this what you want?

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);

    if(angleInDegrees%180==0){
        ctx.drawImage(image, -image.width/2,-image.height/2);
    }else{
        ctx.drawImage(image, -image.width/2,-canvas.width/2,image.width, canvas.width);
    }
    ctx.restore();
}

Upvotes: 1

Related Questions