user3665695
user3665695

Reputation: 3

How to rotate moving canvas object?

I need to move square inside rect using canvas. So I read some posts about canvas and made some canvas. Then I put a little blue square in big rect.

The blue square should move and rotate, but it's not. Please help.

  movingSquare.rotate = function() {
    var x = this.x;
    var y = this.y;
    context.translate(x + 10, y + 10);
    context.rotate((Math.PI / 180) * 45);
    context.translate(-x - 10, -y - 10);
    };

Here is my plunker http://plnkr.co/edit/dKy8qxaZu9BOzlLUWIam?p=info

Upvotes: 0

Views: 581

Answers (1)

Loktar
Loktar

Reputation: 35309

Here is one way to try

The problem is you aren't saving and restoring the context. What happens is you translate so you are saying x and y is where I need to draw, then you are rotating it by 45 degrees, the next time it comes around it translates it to x and y again, and rotates it 45 degrees again so now its rotated 90 degrees, it will keep going on and on.

this.drawRotated = function(color){
    x = this.x;
    y = this.y;
    context.save();
    context.translate(x, y);
    context.rotate((Math.PI / 180) * 45);
    context.fillStyle = color;
    context.fillRect(0, 0, this.width, this.height);
    context.restore();
};

This is how I did it using your plunker, however there are definitely better ways to organize the rendering methods.

Here is the approach I use note, the code is older, but the following is still relevant.

// save the context
ctx.save();
// translate it to the boxes x and boxes y, basically your taking the canvas and moving it to each box.
ctx.translate(box.x, box.y);
// now rotate it
ctx.rotate(box.angle);
// -5 is half of the box width and height 0,0 is the boxes location, im drawing it at half the width and height to set the rotation origin to the center of the box.
ctx.fillRect(-5,-5, 10,10); 
// now restore
ctx.restore();

Upvotes: 3

Related Questions