赤い四角が回転することができます。
回転部品
以前、このチュートリアルでは、赤い四角はgameareaに動き回ることができたが、それがオンまたは回転することができませんでした。
コンポーネントを回転させるには、我々は、コンポーネントを描画する方法を変更する必要があります。
canvas要素のために利用可能な唯一の回転方法は、キャンバス全体を回転させます。

あなたがキャンバスに描く他のすべてはまた、特定のコンポーネントだけでなく、回転されます。
我々はいくつかの変更を加えるする必要が理由ですupdate()
メソッドを:
まず、現在のキャンバスコンテキストオブジェクトを保存します。
ctx.save();
その後、我々はtranslateメソッドを使用して、特定のコンポーネントの中心にキャンバス全体を移動します。
ctx.translate(x, y);

その後、我々は使用して所望の回転を行うrotate()メソッドを:
ctx.rotate( angle );

今、私たちは、キャンバスにコンポーネントを描画する準備ができているが、今我々はそれが翻訳上の位置0,0に中心位置だとそれを描画します(and rotated)キャンバス:
ctx.fillRect(width / -2, height / -2, width, height);

我々が終了すると、私たちは、復元の方法を使用して、戻ってその保存した位置にコンテキストオブジェクトを復元する必要があります:
ctx.restore();
コンポーネントが回転している唯一のものです:

コンポーネントのコンストラクタ
component
コンストラクタが呼ばれる新しいpropery持つangle
成分の角度を表しラジアン数です。
update
の方法component
のコンストラクタであった私たちは、コンポーネントを描画し、ここでは、コンポーネントを回転することを可能にする変更を見ることができます:
例
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();
}
»それを自分で試してみてください