Canvas Translate

Last Updated:

Canvas Translate

ctx.translate() canvas method adds a translation transformation to the current matrix.

Your browser does not support the canvas element.

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.

Example

HTML Online Editor
<!DOCTYPE html> <html lang="en-US"> <body> <canvas id="point" width="90" height="190"> Your browser does not support the canvas element. </canvas> <script> var canvas = document.getElementById('point'); var ctx = canvas.getContext('2d'); // Moved square ctx.translate(0, 100); ctx.fillStyle = '#339933'; 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 = '#8c8c8c'; ctx.fillRect(0, 0, 80, 80); </script> </body> </html>

Syntax

ctx.translate(x, y)

Attributes Value

ValueExplanation
x Specifies the distance to move in the horizontal direction.
  • Positive values are to the right.
  • Negative values to the left.
y Specifies the distance to move in the vertical direction.
  • Positive values are to the down.
  • Negative values to the up.

Share this Page

Meet the Author