CanvasRenderingContext2D: resetTransform() 方法
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 |
瀏覽器相容性
載入中…
另見
- 定義此方法的介面:
CanvasRenderingContext2D