Translatew transform on the HTML5 canvas

Example of how you can use the translate transform on the HTML5 canvas. The rectangle normally would be at coordinates of x:20 and y:20. But using the translate transform we have moved it to the center of the screen accordingly.
<!DOCTYPE HTML>
<html>
  <head>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="600" height="300"></canvas>
    <script>

    var canvas = document.getElementById('myCanvas'); 
    var ctx = canvas.getContext('2d'); 
    
        ctx.translate(canvas.width / 2, canvas.height / 2);

        ctx.fillStyle = 'red';
        ctx.fillRect(20, 20, 100, 100);
       
   </script>
  </body>
</html>      

Responses

0 Replies