CanvasRenderingContext2D.translate() - Web APIs 编辑

The CanvasRenderingContext2D.translate() method of the Canvas 2D API adds a translation transformation to the current matrix.

Syntax

void ctx.translate(x, y);

The translate() method adds a translation transformation to the current matrix by moving the canvas and its origin x units horizontally and y units vertically on the grid.

Parameters

x
Distance to move in the horizontal direction. Positive values are to the right, and negative to the left.
y
Distance to move in the vertical direction. Positive values are down, and negative are up.

Examples

Moving a shape

This example draws a square that is moved from its default position by the translate() method. An unmoved square of the same size is then drawn for comparison.

HTML

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

JavaScript

The translate() method translates the context by 110 horizontally and 30 vertically. The first square is shifted by those amounts from its default position.

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

// Moved square
ctx.translate(110, 30);
ctx.fillStyle = 'red';
ctx.fillRect(0, 0, 80, 80);

// Reset current transformation matrix to the identity matrix
ctx.setTransform(1, 0, 0, 1, 0, 0);

// Unmoved square
ctx.fillStyle = 'gray';
ctx.fillRect(0, 0, 80, 80);

Result

The moved square is red, and the unmoved square is gray.

Specifications

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

Browser compatibility

BCD tables only load in the browser

See also

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

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

发布评论

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

词条统计

浏览:38 次

字数:3697

最后编辑:6年前

编辑次数:0 次

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