从角度矩形的尺寸和位置中寻找顶点

时间:2014-04-13 00:32:54

标签: javascript html5 canvas vector

我试图实现转换矩阵公式:

cos()-sin()

sin()cos()

在下面的Javascript代码中,this.rot.cos =角度的cos和this.rot.sin是角度的sin。

var h1 = this.rot.cos * this.dimension.x,
h2 = this.rot.sin * this.dimension.x,
h3 = this.rot.cos * this.dimension.y,
h4 = this.rot.sin * this.dimension.y;

v = [

{
  x: h1 - h4,
  y: h2 + h3
},

{
  x: -(h1 - h4),
  y: h2 + h3
},

{
  x: -(h1 - h4),
  y: -(h2 + h3)
},

{
  x: h1 - h4,
  y: -(h2 + h3)
}

  ];

 tankBattle.ctx.beginPath();
  tankBattle.ctx.moveTo(v[0].x, v[0].y);
  tankBattle.ctx.lineTo(v[1].x, v[1].y);
  tankBattle.ctx.lineTo(v[2].x, v[2].y);
  tankBattle.ctx.lineTo(v[3].x, v[3].y);
  tankBattle.ctx.lineTo(v[0].x, v[0].y);

我获得的形状与sin和cos波相同,并且在某个程度上变为0(我相信90和270)。我在这里计算顶点是否有问题?

1 个答案:

答案 0 :(得分:1)

看来你的公式出错了,以下是有效的:

http://jsbin.com/wudeqewa/1/edit

function drawTank(x, y, rot)  {

    var cosrot = Math.cos(rot);
    var sinrot = Math.sin(rot);

    var h1 = cosrot * dimension.x,
        h2 = sinrot * dimension.x,
        h3 = cosrot * dimension.y,
        h4 = sinrot * dimension.y;

    v = [{
        x: h1 - h4,
        y: h2 + h3
    },

    {
        x: h1 + h4,
        y: h2 - h3
    },

    {
        x: -h1 + h4,
        y: -h2 - h3
    },

    {
        x: -h1 - h4,
        y: -h2 + h3
    }];

    ctx.save();
    ctx.translate(x, y);
    ctx.beginPath();
    ctx.moveTo(v[0].x, v[0].y);
    ctx.lineTo(v[1].x, v[1].y);
    ctx.lineTo(v[2].x, v[2].y);
    ctx.lineTo(v[3].x, v[3].y);
    ctx.lineTo(v[0].x, v[0].y);
    ctx.stroke();
    ctx.restore();
}