Skip to content
Related Articles

Related Articles

HTML | canvas translate() Method
  • Last Updated : 28 Jun, 2019

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.




<!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>

Output:

Example 2:




<!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

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
Recommended Articles
Page :