Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 610
YemSalat Avatar asked Mar 23 '13 20:03

YemSalat


People also ask

How do I reset canvas rotation in procreate?

And this couldn't be easier with Procreate. To rotate your canvas, put two fingers on your screen and twist your fingers in a circular motion.

How do I reset my canvas orientation?

You can reset via the View menu / Canvas Orientation / Reset Rotation. Or, look at the very bottom right of the screen. You'll see a box labelled 'R' where you enter degrees. Enter zero in the box and hit enter.

How do I reset the canvas rotation in gimp?

Just press Shift and start dragging the middle mouse button up or down. Use the additional Ctrl modifier to rotate with 15° step. To reset the rotation either choose “View / Rotate / Reset to 0°” command in menu or use Ctrl + Shift + dragging.


1 Answers

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();
like image 90
YemSalat Avatar answered Sep 28 '22 08:09

YemSalat