Question

I have an image on my webpage with some little editing functionality. One of the functionalities i want to have is rotating Image by some degrees. My html looks like this

<img src="path/to/image" id="myimage">

js file

$(document).ready(function (){
    caman = Caman("#myimage");
);

I want to rotate my image. So i tried executing the following commands

image = new Image();
image.src = caman.canvas.toDataURL(); //to get the image src
canvas = caman.canvas; //to get caman's canvas
ctx = caman.context;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width/2, canvas.height/2);
ctx.rotate(10*Math.PI/180) //10 degrees clockwise correct?
ctx.drawImage(image, image.width/-2, image.height/-2);

while the image rotates as it should and in the right position, some of the image gets cut off because the canvas is exactly as the size of the image and when the image rotates the edges e.g go outside canvas therefore not shown. How can I change this behaviour...Should I always have a larger canvas than my image?

Was it helpful?

Solution

Yes, you canvas needs to be sized so the rotated image fits inside it.

One way of doing this is finding the bounds like this:

function getBounds(w, h, radians){

    var a = Math.abs(Math.cos(radians)),
        b = Math.abs(Math.sin(radians));

    return {h: h * a + w * b,
            w: h * b + w * a}
}

Now you will have the bounds or size you need for the canvas for the image to fit inside at that specific angle. I have written a little more about finding bounds in this article including finding max bound for any angle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top