在HTML5 Canvas中在其轴上旋转方块?

时间:2012-01-20 06:48:53

标签: javascript html5 html5-canvas rect

我想创建一个在轴上旋转方形的函数。

var halfWidth = canvas.width/2;
var halfHeight = canvas.height/2;

var x = halfWidth-10;
var y = halfHeight-10;
var w = 20;
var h = 20;
var deg = 45;

rotate(x, y, w, h, deg);

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

功能:

function rotate(x, y, w, h, deg) {
    // ctx.translate() and ctx.rotate()
    // goes here.
}

怎么做?

3 个答案:

答案 0 :(得分:4)

感谢dr.dredel获取该链接。

var cx = canvas.width/2;
var cy = canvas.height/2;

var x = -10;
var y = -10;
var w = 20;
var h = 20;
var deg = 45;

ctx.save();

ctx.translate(cx, cy);
ctx.rotate(deg * Math.PI/180);

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

ctx.restore();

说明:

  • ctx.save()保存坐标系的当前状态。

  • ctx.translate(cx, cy)将原点更改为画布中心

  • ctx.rotate(deg * Math.PI/180)将方块旋转到45度(注意参数是弧度,而不是度数)

  • ctx.fillRect( x, y, w, h )绘制正方形

  • ctx.restore()恢复坐标系的最后一个状态。

JS Fiddle link

Another JS Fiddle link, with a HTML5 slider

答案 1 :(得分:0)

如果我没记错的话,所涉及的翻译首先要转换为矩形的中心点,然后旋转想要的数量,然后绘制。或者可能先旋转,然后翻译,我有点生锈=)

答案 2 :(得分:0)

这是我的意见:

<强> JAVASCRIPT

var canvas = document.getElementById("myCanvas");
var ctx2 = canvas.getContext("2d");
ctx2.fillStyle='#333';

ctx2.fillRect(50,50,100,100);
var ctx = canvas.getContext("2d");


ctx.fillStyle='red';

var deg = Math.PI/180;

ctx.save();
    ctx.translate(100, 100);
    ctx.rotate(45 * deg);
    ctx.fillRect(-50,-50,100,100);
ctx.restore();

ctx2是旧位置,ctx是形状的新位置。您必须根据您想要定位形状的位置使用相同的x,y坐标转换形状。然后你必须输入值ctx.fillRect(x,y,w,h);保持x和y作为-ve值(高度和宽度的一半,以保持它在画布的对角线上,否则改变操纵它)。和h,w作为你想要的值。

<强> DMEO