- HTML Canvas Tutorial
- HTML Canvas - Home
- HTML Canvas - Introduction
- Environmental Setup
- HTML Canvas - First Application
- HTML Canvas - Drawing 2D Shapes
- HTML Canvas - Path Elements
- 2D Shapes Using Path Elements
- HTML Canvas - Colors
- HTML Canvas - Adding Styles
- HTML Canvas - Adding Text
- HTML Canvas - Adding Images
- HTML Canvas - Canvas Clock
- HTML Canvas - Transformations
- Composting and Clipping
- HTML Canvas - Basic Animations
- Advanced Animations
- HTML Canvas API Functions
- HTML Canvas - Element
- HTML Canvas - Rectangles
- HTML Canvas - Lines
- HTML Canvas - Paths
- HTML Canvas - Text
- HTML Canvas - Colors and Styles
- HTML Canvas - Images
- HTML Canvas - Shadows and Transformations
- HTML Canvas Useful Resources
- HTML Canvas - Quick Guide
- HTML Canvas - Useful Resources
- HTML Canvas - Discussion
HTML Canvas - translate() Method
The HTML Canvas translate() method of Canvas API adds a translation matrix to the current matrix inside the Canvas element.
Syntax
Following is the syntax of HTML Canvas translate() method
CanvasRenderingContext2D.translate(x, y);
Parameters
Following is the list of parameters of this method −
S.No | Parameter & Description |
---|---|
1 | x Distance to move in the horizontal direction. |
2 | y Distance to move in the vertical direction. |
Return value
It returns the translated transformation matrix of the object when this method is called.
Example
The following example translates the Canvas co-ordinates and draws a rectangle onto the Canvas element using the HTML Canvas translate() method.
<!DOCTYPE html> <html lang="en"> <head> <title>Reference API</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body> <canvas id="canvas" width="250" height="200" style="border: 1px solid black;"></canvas> <script> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.translate(10, 10); context.fillStyle = 'blue'; context.fillRect(25, 25, 150, 100); </script> </body> </html>
Output
The output returned by the following code on the webpage as −
Example
The following example translates a line onto the Canvas element using the method translate().
<!DOCTYPE html> <html lang="en"> <head> <title>Reference API</title> <style> body { margin: 10px; padding: 10px; } </style> </head> <body> <canvas id="canvas" width="150" height="150" style="border: 1px solid black;"></canvas> <script> var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); context.translate(10, 10); context.strokeStyle = 'blue'; context.moveTo(10, 10); context.lineTo(100, 100); context.stroke(); </script> </body> </html>
Output
The output returned by the following code on the webpage as −
To Continue Learning Please Login
Login with Google