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 −

HTML Canvas Translate Method

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 −

HTML Canvas Translate Method
html_canvas_shadows_and_transformations.htm
Advertisements