Saturday, May 22, 2010

Rotating Images on A Canvas

I was having some humongous trouble getting the canvas to rotate properly in the following example. I wanted actors to move around the stage in a meaningful way. I've learned that to get the actors to move you can draw the images in different places or you can save the canvas, translate the canvas, draw the image to the screen and then reset the canvas. This will effectively move around the image. I don't know which way is faster. The following code snippet uses the latter method. In order to get the actors to rotate you have to save the canvas, rotate the canvas, draw the image and then reset the canvas. Well this will do some funny things because you are not rotating the canvas where the actor is, you are rotating (by default) from the center. So what you have to do is something like this:

Actor.prototype.draw = function() {
   if (this.image.isReady) {;
    context.translate(this.dx, this.dy);
    var rotateX = this.x+this.width/2;
    var rotateY = this.y+this.height/2;
    context.translate(rotateX, rotateY);
    context.translate(-rotateX, -rotateY);
    context.drawImage(this.image, this.x, this.y, this.width, this.height);

I will be posting a demo soon!


The real key to make this happen though was this simple code posted by caleb_h at!:

No comments:

Post a Comment