The CanvasRenderingContext2D.translate()
method of the Canvas 2D API adds a translation transformation to the current matrix.
The CanvasRenderingContext2D.translate()
method of the Canvas 2D API adds a translation transformation to the current matrix.
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.
None (undefined
).
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.
The translate()
method translates the context by 110 horizontally and 30 vertically. The first square is shifted by those amounts from its default position.
js
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.
Specification |
---|
HTML Standard # dom-context-2d-translate-dev |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
translate |
1 | 12 | 1.5 | 9 | ≤12.1 | 2 | 4.4 | 18 | 4 | ≤12.1 | 1 | 1.0 |
CanvasRenderingContext2D
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/translate