CanvasRenderingContext2D: resetTransform() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流浏览器均已支持。

CanvasRenderingContext2D.resetTransform() 方法是 Canvas 2D API 的一部分,它会将当前的变换重置为标识矩阵。

语法

js
resetTransform()

参数

无。

返回值

无(undefined)。

示例

重置矩阵

本示例在修改矩阵后绘制了一个旋转的矩形,然后使用 resetTransform() 方法重置矩阵。

HTML

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

JavaScript

rotate() 方法将变换矩阵旋转 45°。fillRect() 方法绘制一个填充矩形,该矩形根据该矩阵进行调整。

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

// Draw a rotated rectangle
ctx.rotate((45 * Math.PI) / 180);
ctx.fillRect(60, 0, 100, 30);

// Reset transformation matrix to the identity matrix
ctx.resetTransform();

结果

继续使用常规矩阵

在完成变换形状的绘制后,您应该在渲染其他任何内容之前调用 resetTransform()。在本示例中,前两个形状使用倾斜变换绘制,最后两个形状使用标识(常规)变换绘制。

HTML

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

JavaScript

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

// Skewed rectangles
ctx.transform(1, 0, 1.7, 1, 0, 0);
ctx.fillStyle = "gray";
ctx.fillRect(40, 40, 50, 20);
ctx.fillRect(40, 90, 50, 20);

// Non-skewed rectangles
ctx.resetTransform();
ctx.fillStyle = "red";
ctx.fillRect(40, 40, 50, 20);
ctx.fillRect(40, 90, 50, 20);

结果

倾斜的矩形是灰色的,未倾斜的矩形是红色的。

polyfill

您还可以使用 setTransform() 方法将当前变换重置为标识矩阵,如下所示:

js
ctx.setTransform(1, 0, 0, 1, 0, 0);

规范

规范
HTML
# dom-context-2d-resettransform-dev

浏览器兼容性

另见