HTML | canvas translate() Method

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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 contex = geeks.getContext("2d");
            contex.translate(250, 110); //contex.translate(x, y);
            contex.fillStyle = "#00FF00";
            contex.fillRect(20, 20, 150, 100);
        </script>
  
    </center>
</body>
  
</html>

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!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 contex = geeks.getContext("2d");
            contex.rect(00, 00, 150, 100);
            contex.fillStyle = "green";
            contex.fill();
            contex.stroke();
  
            contex.translate(250, 50);
            contex.rect(100, 100, 150, 100);
            contex.fillStyle = "";
            contex.fill();
            contex.stroke();
        </script>
    </center>
</body>
  
</html

chevron_right


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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.