HTML5 の canvas 回転 |
作成日:2020-04-09 最終更新日: |
回転のコマンドは原点のまわりのみである。従って、任意の点の回転を実現したい場合は、 座標の移動が必要となる。
// 長方形の中心で回転する // 青色の長方形を描く ctx.save(); ctx.fillStyle = "#0095DD"; ctx.fillRect(150, 30, 100, 90); // 幅 100, 高さ 90 ctx.translate(200, 75); // 長方形の中心に移動する // x = x + 幅 / 2 (200 = 150 + 100 / 2) // y = y + 高さ / 2 (75 = 30 + 90 / 2) ctx.rotate((Math.PI/180)*25); // 反時計回りに 25 度回転する ctx.translate(-200, -75); // 元の位置に移動する // 青色の矩形を描く ctx.fillStyle = "#4D4E53"; ctx.fillRect(150, 30, 100, 100); ctx.restore();
https://developer.mozilla.org/ja/docs/Web/Guide/HTML/Canvas_tutorial が役に立つ。