Canvas Translate
## HTML Canvas `translate()` Method
The `translate()` method is a powerful transformation tool in the HTML Canvas 2D API. It is used to remap the $(0,0)$ origin position on the canvas coordinate system, allowing you to move the drawing origin to a new location.
When you call drawing methods (like `fillRect()`) after calling `translate()`, the translation values are added to the $x$ and $y$ coordinate values of your drawing commands.
---
## Syntax and Usage
The `translate()` method shifts the canvas and its origin $(0,0)$ horizontally and vertically.
```javascript
context.translate(x, y);
```
### Parameter Values
| Parameter | Type | Description |
| :--- | :--- | :--- |
| `x` | Number | The distance to move the coordinate system in the horizontal (X-axis) direction, in pixels. Positive values move right, negative values move left. |
| `y` | Number | The distance to move the coordinate system in the vertical (Y-axis) direction, in pixels. Positive values move down, negative values move up. |
---
## Code Examples
### Example 1: Basic Translation
In this example, we draw a rectangle at `(10, 10)`, translate the canvas origin to `(70, 70)`, and then draw the same rectangle at `(10, 10)` relative to the new origin. Notice how the second rectangle is drawn at the absolute position of `(80, 80)`.
```html
```
---
## Key Considerations & Best Practices
### 1. Transformations are Cumulative
When you call `translate()` multiple times, the transformations accumulate. For example:
```javascript
ctx.translate(50, 50); // Origin is now at (50, 50)
ctx.translate(20, 30); // Origin is now at (70, 80)
```
### 2. Saving and Restoring State
Because transformations accumulate, it is highly recommended to use `ctx.save()` before translating and `ctx.restore()` after you finish drawing. This prevents your translation from affecting subsequent drawing operations.
```javascript
ctx.save(); // Save the clean canvas state
ctx.translate(100, 50); // Move origin
ctx.fillRect(0, 0, 50, 50); // Draw at the translated origin
ctx.restore(); // Restore origin back to (0,0)
```
### 3. Use Cases
* **Simplified Math:** It is often easier to translate the origin to the center of an object, draw it relative to `(0,0)`, and then restore the state.
* **Rotation:** The `rotate()` method always rotates around the current origin `(0,0)`. To rotate an object around its own center, you must first `translate()` the origin to the object's center, perform the `rotate()`, and draw the object centered at `(0,0)`.
---
## Browser Support
The `translate()` method is supported by all modern web browsers:
* Google Chrome
* Mozilla Firefox
* Microsoft Edge / Internet Explorer 9+
* Safari
* Opera
*Note: Internet Explorer 8 and earlier versions do not support the `
YouTip