JavaScript Translate

Summary: in this tutorial, you’ll learn how to use the JavaScript translate() API to move the origin of the canvas to the new position.

Introduction to the JavaScript translate() method.

The translate() is a method of a 2D drawing context. The translate(x,y) method moves the canvas and its origin x units horizontally and y units vertically.

The following illustrates the syntax of the translate() method:

ctx.translate(x, y);Code language: CSS (css)

In this syntax:

  • x represents the distance that you want to move the origin of the canvas in the horizontal direction. The origin moves to the left if x is positive and to the right in case x is negative.
  • y represents the distance that you want to move the origin of the canvas in the vertical direction. The origin moves down if y is positive and up if y is negative.

By default, the origin of the canvas (0,0) is at the top left of the screen. By adding a translation transformation, the whole coordinate system moves so that its new origin locates at (x,y):