HTML5 Game - Translation with translate() method

Introduction

The translate method moved the origin of the 2d rendering context.

This is how to call the translate method:

  
context.translate(150, 150);  

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
               /*from   w  w w.  j a  v a2s. com*/
                context.fillStyle = "red";   
                context.fillRect(50, 50, 100, 100);  

                context.translate(50, 50);  
  
                context.fillStyle = "blue";  
                context.fillRect(50, 50, 100, 100);  

            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

The two arguments are the (x , y) coordinate values.

It sets how far to move the origin of the 2d rendering context.

The (x, y) coordinate values provided are added on to the existing translation of the origin, which is (0, 0) by default.

Every transformation method, including translate, affects all elements drawn after it has been called.

Related Topic