简体   繁体   中英

Rotating an image in canvas keeping to the top left

I am trying to rotate an image inside a canvas but keeping the image to the top left. I have managed to get it to stay to the top left but only on the first and second rotation steps.

The rotation steps I would like are:

在此处输入图片说明

I would also like it to scale well depending on screen size which I have already done. Sorry for the short description but I have made a fiddle. As you can see the 3rd and 4th steps the image is taken off the canvas which is wrong.

Here is the fiddle: http://jsfiddle.net/jNWT5/1/

The area of the code that is performing the transform is:

function rotate() {

    ctx.clearRect(0, 0, cDimensions.width, cDimensions.height);

    ctx.translate(pasteH,0); 

    ctx.rotate(90 * Math.PI / 180);

    pasteImage();

}   

Any help is greatly appreciated.

You're on the right track!

  • First translate to where you want the rotation point to be (in your case 0,0). Since the default canvas rotation point is 0,0 this step is optional in your case.

  • Next rotate the canvas through your 4 rotations: 0, PI/2, PI, PI*1.5.

  • Finally drawImage with the appropriate offsets that you desire (in your case to pull the image over to 0,0)

在此处输入图片说明在此处输入图片说明

在此处输入图片说明在此处输入图片说明

Here's an array with the angle and offsets needed for your 4 rotations:

var rotations=[];
rotations.push({angle:0,offsetX:0,offsetY:0});
rotations.push({angle:PI/2,offsetX:0,offsetY:-img.height});
rotations.push({angle:PI,offsetX:-img.width,offsetY:-img.height});
rotations.push({angle:PI*1.5,offsetX:-img.width,offsetY:0});

Heres a Demo: http://jsfiddle.net/m1erickson/ryA8f/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM