HTML5 Game - Creating a mirror transform

Introduction

The following code uses scale transformation to mirror the canvas context horizontally.

Then write out some backwards text.

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  a 2s . c  o m*/
                // translate context to center of canvas
                context.translate(canvas.width / 2, canvas.height / 2);
                
                // flip context horizontally
                context.scale(-1, 1);
                
                context.font = "30pt Calibri";
                context.textAlign = "center";
                context.fillStyle = "blue";
                context.fillText("Hello java2s.com!", 0, 0);
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

Note

To create a mirror transform, assign a negative value to sx or sy to the scale method:

context.scale(-sx,-sy); 

Related Topic