CanvasRenderingContext2D: rotate() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

CanvasRenderingContext2D.rotate() 方法(Canvas 2D API 的一部分)向變換矩陣新增一個旋轉。

語法

js
rotate(angle)

Rectangular coordinate system with the rotation of the abscissa axis by the alpha angle

引數

angle

旋轉角度,以弧度為單位,順時針旋轉。你可以使用 degree * Math.PI / 180 來根據度計算弧度。

旋轉的中心點始終是畫布的原始座標 (origin)。要更改旋轉中心點,你需要使用 translate() 方法來移動畫布。

返回值

無(undefined)。

示例

旋轉圖形

本示例將一個矩形旋轉 45°。請注意,旋轉的中心是畫布的左上角,而不是相對於任何圖形的位置。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Point of transform origin
ctx.arc(0, 0, 5, 0, 2 * Math.PI);
ctx.fillStyle = "blue";
ctx.fill();

// Non-rotated rectangle
ctx.fillStyle = "gray";
ctx.fillRect(100, 0, 80, 20);

// Rotated rectangle
ctx.rotate((45 * Math.PI) / 180);
ctx.fillStyle = "red";
ctx.fillRect(100, 0, 80, 20);

// Reset transformation matrix to the identity matrix
ctx.setTransform(1, 0, 0, 1, 0, 0);

結果

旋轉中心是藍色的。未旋轉的矩形是灰色的,旋轉後的矩形是紅色的。

圍繞圖形中心旋轉

本示例將圖形圍繞其中心點進行旋轉。為此,將執行以下步驟來操作矩陣:

  1. 首先,translate() 將矩陣的原點移動到圖形的中心。
  2. rotate() 按所需量旋轉矩陣。
  3. 最後,translate() 將矩陣的原點移回其初始位置。這是透過以負方向應用圖形中心座標的值來實現的。

HTML

html
<canvas id="canvas"></canvas>

JavaScript

該圖形是一個矩形,其角點位於 (80, 60),寬度為 140,高度為 30。其水平中心位於 (80 + 140 / 2),即 150。其垂直中心位於 (60 + 30 / 2),即 75。因此,中心點位於 (150, 75)。

js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Non-rotated rectangle
ctx.fillStyle = "gray";
ctx.fillRect(80, 60, 140, 30);

// Matrix transformation
ctx.translate(150, 75);
ctx.rotate(Math.PI / 2);
ctx.translate(-150, -75);

// Rotated rectangle
ctx.fillStyle = "red";
ctx.fillRect(80, 60, 140, 30);

結果

未旋轉的矩形是灰色的,旋轉後的矩形是紅色的。

規範

規範
HTML
# dom-context-2d-rotate-dev

瀏覽器相容性

另見