views:

326

answers:

2

I'm having trouble roating an image around itself using Canvas.

Since you can't rotate an image you have to rotate the canvas: if I rotate the canvas by a degree the origin around which I want to rotate changes. I don't get how to track this change.

This is my current code: http://pastie.org/669023

And a demo is at http://preview.netlashproject.be/cog/

If you want to give things a shot the zipped up code and image is at http://preview.netlashproject.be/cog/cog.zip

+1  A: 

it looks like this could be something you could use: http://wilq32.googlepages.com/wilq32.rollimage222

here's a test of it: http://www.antiyes.com/test/index.php

John Boker
I'd like to use code that I actually understand and keep it simple.
Wolfr
you could have a look at the plugin code and see how it's done.
John Boker
I know, I did. It seems to me there is a much simpler way using only canvas.
Wolfr
starting around line 308 there are about 6 or 7 lines of code that rotates the image with a canvas. it looks pretty simple, the key is to translate it before rotating.
John Boker
+5  A: 

I fixed your code:

var rotation = 0;
function draw(){

  var ctx = document.getElementById('myCanvas').getContext('2d');
  ctx.globalCompositeOperation = 'destination-over';

  ctx.save();
  ctx.clearRect(0,0,200,200);
  ctx.translate(100,100); // to get it in the origin
  rotation +=1;
  ctx.rotate(rotation*Math.PI/64); //rotate in origin
  ctx.translate(-100,-100); //put it back
  ctx.drawImage(cog,0,0);
  ctx.restore();
}

The important thing here is that you have to translate the image to the origin first before rotating, and translate it back!

DaMacc
That works great, thanks!
Wolfr