【问题标题】:How to rotate moving canvas object?如何旋转移动的画布对象?
【发布时间】:2014-07-11 18:31:47
【问题描述】:

我需要使用画布在矩形内移动正方形。所以我阅读了一些关于画布的帖子并制作了一些画布。然后我在大矩形中放了一个蓝色的小方块。

蓝色方块应该移动和旋转,但事实并非如此。请帮忙。

  movingSquare.rotate = function() {
    var x = this.x;
    var y = this.y;
    context.translate(x + 10, y + 10);
    context.rotate((Math.PI / 180) * 45);
    context.translate(-x - 10, -y - 10);
    };

这是我的笨蛋http://plnkr.co/edit/dKy8qxaZu9BOzlLUWIam?p=info

【问题讨论】:

  • 它在 Chrome 和 Firefox 中为我移动和旋转。
  • 不正确:p @TylerH

标签: html canvas rotation html5-canvas rotatetransform


【解决方案1】:

Here is one way to try

问题是您没有保存和恢复上下文。发生的事情是你翻译所以你说 x 和 y 是我需要绘制的地方,然后你将它旋转 45 度,下一次它绕过来时它再次将它转换为 x 和 y,并将它旋转 45 度 再次所以现在它旋转了 90 度,它会继续下去。

this.drawRotated = function(color){
    x = this.x;
    y = this.y;
    context.save();
    context.translate(x, y);
    context.rotate((Math.PI / 180) * 45);
    context.fillStyle = color;
    context.fillRect(0, 0, this.width, this.height);
    context.restore();
};

这就是我使用你的 plunker 的方法,但是肯定有更好的方法来组织渲染方法。

Here is the approach I use 注意,代码较旧,但以下代码仍然相关。

// save the context
ctx.save();
// translate it to the boxes x and boxes y, basically your taking the canvas and moving it to each box.
ctx.translate(box.x, box.y);
// now rotate it
ctx.rotate(box.angle);
// -5 is half of the box width and height 0,0 is the boxes location, im drawing it at half the width and height to set the rotation origin to the center of the box.
ctx.fillRect(-5,-5, 10,10); 
// now restore
ctx.restore();

【讨论】:

    猜你喜欢
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多