HTML5 Game - Canvas Translate

Introduction

The following code shows how to move the context to a new location on the canvas.

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  a2 s .  c  om*/
                let rectWidth = 150;
                let rectHeight = 75;
                
                // translate context to center of canvas
                context.translate(canvas.width / 2, canvas.height / 2);
                
                context.fillStyle = "blue";
                context.fillRect(-rectWidth / 2, -rectHeight / 2, rectWidth, rectHeight);
            }; 
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

HTML5 canvas transformations transforms the canvas context in some way and then draw onto the canvas.

The code above translated the canvas context such that the top-left corner of the context has moved to the center of the canvas:

context.translate(tx,ty); 

The tx parameter sets the horizontal translation.

The ty parameter sets the vertical translation.

After the context transformation, we draw a rectangle centered on the top-left corner of the canvas context.

In this way we moved a translated rectangle to the center of the canvas.

Related Topics