HTML Canvas Context translate to center

Introduction

The following code 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 corresponds to the horizontal translation.

The ty parameter corresponds to the vertical translation.

Once the context has been transformed, we can draw a rectangle centered on the top-left corner of the canvas context.

View in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                /*from w ww .j av a  2 s  .  c om*/
                var rectWidth = 150;
                var 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>



PreviousNext

Related