游戏旋转
红色方块可以旋转
旋转组件
在本教程的早期,红色方块可以在游戏区域内移动,但无法转动或旋转。
要旋转组件,我们必须改变绘制组件的方式。
canvas 元素唯一可用的旋转方法将旋转整个 canvas。

您在 canvas 上绘制的所有内容也将被旋转,而不仅仅是特定组件。
因此,我们需要在 update()
方法中进行一些更改。
首先,我们保存当前的 canvas 上下文对象。
ctx.save();
然后,我们使用 translate 方法将整个 canvas 移动到特定组件的中心。
ctx.translate(x, y);

然后,我们使用 rotate() 方法执行所需的旋转。
ctx.rotate(angle);

现在,我们可以在 canvas 上绘制组件了,但现在我们将以其中心位置在转换后的(和旋转后的) canvas 的 0,0 位置绘制它。
ctx.fillRect(width / -2, height / -2, width, height);

完成后,我们必须使用 restore 方法将上下文对象恢复到其保存的位置。
ctx.restore();
组件是唯一旋转的部分。

组件构造函数
名为 component
的构造函数有一个名为 angle
的新属性,它是一个弧度数,表示组件的角度。
名为 component
的构造函数的 update
方法是绘制组件的地方,您可以在此处看到允许组件旋转的更改。
示例
function component(width, height, color, x, y) {
this.width = width;
this.height = height;
this.angle = 0;
this.x = x;
this.y = y;
this.update = function() {
ctx = myGameArea.context;
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.angle);
ctx.fillStyle = color;
ctx.fillRect(this.width / -2, this.height / -2, this.width, this.height);
ctx.restore();
}
}
function updateGameArea() {
myGameArea.clear();
myGamePiece.angle += 1 * Math.PI / 180;
myGamePiece.update();
}
自己动手试一试 »