CanvasRenderingContext2D.rotate() - Web APIs 编辑

The CanvasRenderingContext2D.rotate() method of the Canvas 2D API adds a rotation to the transformation matrix.

Syntax

void ctx.rotate(angle);

Parameters

angle
The rotation angle, clockwise in radians. You can use degree * Math.PI / 180 to calculate a radian from a degree.

The rotation center point is always the canvas origin. To change the center point, you will need to move the canvas by using the translate() method.

Examples

Rotating a shape

This example rotates a rectangle by 45°. Note that the center of rotation is the top-left corner of the canvas, and not a location relative to any shape.

HTML

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

JavaScript

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);

Result

The center of rotation is blue. The non-rotated rectangle is gray, and the rotated rectangle is red.

Rotating a shape around its center

This example rotates a shape around its center point. To do this, the following steps are applied to the matrix:

  1. First, translate() moves the matrix's origin to the shape's center.
  2. rotate() rotates the matrix by the desired amount.
  3. Finally, translate() moves the matrix's origin back to its starting point. This is done by applying the values of the shape's center coordinates in a negative direction.

HTML

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

JavaScript

The shape is a rectangle with its corner at (80, 60), a width of 140, a height of 30. Its horizontal center is at (80 + 140 / 2), or 150. Its vertical center is at (60 + 30 / 2), or 75. Thus, the center point is at (150, 75).

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);

Result

The non-rotated rectangle is gray, and the rotated rectangle is red.

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'CanvasRenderingContext2D.rotate' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:106 次

字数:5631

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文