Open In App
Related Articles

HTML canvas translate() Method

Improve Article
Improve
Save Article
Save
Like Article
Like

The HTML canvas translate() Method is used to specify that the object is translated by given translate amount. Syntax:

context.translate(x, y)

Parameter Values:

  • x: It stores the value, that how much the canvas will move left or right means x-axis wise.
  • y: It stores the value, that how much the canvas will move up and down means y-axis wise.

Example 1: Here you can check by changing the x-axis and y-axis. 

html




<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML canvas translate() Method
    </title>
</head>
  
<body>
    <center>
        <h1 style="color:green">GeeksforGeeks</h1>
        <canvas id="GFG" width="500" height="250" 
                     style="border:2px solid gray">
        </canvas>
  
        <script>
            var geeks = document.getElementById("GFG");
            var context = geeks.getContext("2d");
            context.translate(250, 110); //context.translate(x, y);
            context.fillStyle = "#00FF00";
            context.fillRect(20, 20, 150, 100);
        </script>
  
    </center>
</body>
  
</html>

Output: Example 2: 

html




<!DOCTYPE html>
<html>
  
<head>
    <title>
        HTML canvas translate() Method
    </title>
</head>
  
<body>
    <center>
        <h1 style="color:green">GeeksforGeeks</h1>
        <canvas id="GFG" width="500" height="250" 
                style="border:2px solid gray">
        </canvas>
  
        <script>
            var geeks = document.getElementById("GFG");
            var context = geeks.getContext("2d");
            context.rect(00, 00, 150, 100);
            context.fillStyle = "green";
            context.fill();
            context.stroke();
  
            context.translate(250, 50);
            context.rect(100, 100, 150, 100);
            context.fillStyle = "";
            context.fill();
            context.stroke();
        </script>
    </center>
</body>
  
</html

Output: Note: If you call fillRect() method after translate() method, the value is added to the x- and y-coordinate values. Supported Browsers:

  • Google Chrome
  • Internet Explorer 9.0 or above
  • Firefox
  • Safari
  • Opera

Last Updated : 12 Jun, 2023
Like Article
Save Article
Similar Reads
Related Tutorials