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

浏览器兼容性

另见