Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

HTML | canvas translate() Method

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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

My Personal Notes arrow_drop_up
Last Updated : 06 Feb, 2023
Like Article
Save Article
Similar Reads
Related Tutorials