Open In App

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:



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






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


Article Tags :