CanvasRenderingContext2D.resetTransform() - Web APIs 编辑

Experimental

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The CanvasRenderingContext2D.resetTransform() method of the Canvas 2D API resets the current transform to the identity matrix.

Syntax

void ctx.resetTransform();

Examples

Resetting the matrix

This example draws a rotated rectangle after modifying the matrix, and then resets the matrix using the resetTransform() method.

HTML

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

JavaScript

The rotate() method rotates the transformation matrix by 45°. The fillRect() method draws a filled rectangle, adjusted according to that matrix.

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

Result

Continuing with a regular matrix

Whenever you're done drawing transformed shapes, you should call resetTransform() before rendering anything else. In this example, the first two shapes are drawn with a skew transformation, and the last two are drawn with the identity (regular) transformation.

HTML

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

JavaScript

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

Result

The skewed rectangles are gray, and the non-skewed rectangles are red.

Polyfill

You can also use the setTransform() method to reset the current transform to the identity matrix, like so:

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

Specifications

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

Browser compatibility

BCD tables only load in the browser

See also

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

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

发布评论

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

词条统计

浏览:87 次

字数:5143

最后编辑:6 年前

编辑次数:0 次

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