概要: このチュートリアルでは、JavaScript rotate()
メソッドを使用してキャンバス描画オブジェクトを回転させる方法について解説します。
JavaScript rotate() canvas API の概要
rotate()
は 2D 描画コンテキストのメソッドです。rotate() メソッドを使用すると、キャンバス上の描画オブジェクトを回転できます。
以下は rotate()
メソッドの構文です
ctx.rotate(angle)
Code language: CSS (css)
rotate()
メソッドはラジアン単位での回転角度を採用します。
角度が正の場合、時計回りに回転します。角度が負の場合、反時計回りに回転します。
度をラジアンに変換するには、以下の数式を使用します。
degree * Math.PI / 180
Code language: JavaScript (javascript)
rotate()
メソッドは回転を追加するとき、キャンバスの原点を回転の中心点として使用します。
次の図は回転を図解しています。

回転の中心点を変更する場合は、translate()
メソッドを使用してキャンバスの原点を移動する必要があります。
JavaScript rotate() の例
以下の例では、キャンバスの中心点から始まる赤い長方形を描画します。その後、キャンバスの原点をキャンバスの中心点に移動し、2 番目の長方形を 45 度回転させて描画します。
HTML
<canvas id="canvas" height="300" width="500">
</canvas>
Code language: HTML, XML (xml)
JavaScript
const canvas = document.querySelector('#canvas');
if (canvas.getContext) {
// rectangle's width and height
const width = 150,
height = 20;
// canvas center X and Y
const centerX = canvas.width / 2,
centerY = canvas.height / 2;
const ctx = canvas.getContext('2d');
// a red rectangle
ctx.fillStyle = 'red';
ctx.fillRect(centerX, centerY, width, height);
// move the origin to the canvas' center
ctx.translate(centerX, centerY);
// add 45 degrees rotation
ctx.rotate(45 * Math.PI / 180);
// draw the second rectangle
ctx.fillStyle = 'rgba(0,0,255,0.5)';
ctx.fillRect(0, 0, width, height);
}
Code language: JavaScript (javascript)
出力

概要
- JavaScript
rotate()
メソッドを使用して、キャンバス上の描画オブジェクトを回転できます。
このチュートリアルは参考になりましたか?