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


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.

A canvas's origin moved on the x and y axes based on the values of the translate method.



Distance to move in the horizontal direction. Positive values are to the right, and negative to the left.


Distance to move in the vertical direction. Positive values are down, and negative are up.

Return value

None (undefined).


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.


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


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


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


HTML Standard
# dom-context-2d-translate-dev

Browser compatibility

BCD tables only load in the browser

See also