javascript - Canvas rotation doesn't work properly - Stack Overflow

I am having troubles trying to rotate a rectangle via JavascriptCanvas API.Here is the code:G = {};

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: /

Any clarification is really wele!

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/5YZbd/1/

Any clarification is really wele!

Share Improve this question edited Mar 23, 2013 at 20:42 YemSalat asked Mar 23, 2013 at 20:33 YemSalatYemSalat 21.6k13 gold badges48 silver badges51 bronze badges 3
  • 1 you have an error in your syntax: G.rotate should be G.ctx.rotate. – Fede Commented Mar 23, 2013 at 20:38
  • Cheers, fixed that, but still not working – YemSalat Commented Mar 23, 2013 at 20:41
  • 2 It's drawing, it's just off the screen. Make your canvas bigger: jsfiddle/QHRkR/1 – Xymostech Commented Mar 23, 2013 at 20:44
Add a ment  | 

1 Answer 1

Reset to default 5

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();

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744956775a4603239.html

相关推荐

  • javascript - Canvas rotation doesn't work properly - Stack Overflow

    I am having troubles trying to rotate a rectangle via JavascriptCanvas API.Here is the code:G = {};

    2天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信