YemSalat
YemSalat

Reputation: 21486

Canvas rotation doesn't work properly

I am having troubles trying to rotate a rectangle via JavascriptCanvas API.

Here is the code:

G = {};
// get canvas context
G.ctx = document.getElementById('canvas').getContext('2d');

var x = 200;
var y = 100;
var w = 30;
var h = 70;

G.ctx.fillRect(x, y, w, h);

// Why is this not working??
G.ctx.save();
G.ctx.translate(x, y);
G.ctx.rotate(30*(Math.PI/180));
G.ctx.fillRect(x, y, w, h);
G.ctx.restore();

The code only draws the first rectangle for some reason.

Here is the JSfiddle: http://jsfiddle.net/5YZbd/1/

Any clarification is really welcome!

Upvotes: 6

Views: 5001

Answers (1)

YemSalat
YemSalat

Reputation: 21486

I figured it out.

As soon as I translate the canvas to rectangle's x/y - its position should be referred to as 0/0, cause thats where the canvas origin is after the translation.

Here is the working code:

G.ctx.save();
G.ctx.translate(x, y);
G.ctx.rotate(30*(Math.PI/180));
G.ctx.fillRect(0, 0, w, h);
G.ctx.restore();

Upvotes: 5

Related Questions