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

句法

void ctx.translate(x, y);
					

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.

参数

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.

范例

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

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

结果

moved square is red ,和 unmoved square is gray .

规范

规范 状态 注释
HTML 实时标准
The definition of 'CanvasRenderingContext2D.translate' in that specification.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
translate Chrome Yes Edge 12 Firefox 1.5 IE Yes Opera Yes Safari Yes WebView Android Yes Chrome Android Yes Firefox Android 4 Opera Android Yes Safari iOS Yes Samsung Internet Android Yes

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改: