Canvas How to - Flip context horizontally








Question

We would like to know how to flip context horizontally.

Answer


<html>
    <head>
        <script> 
            window.onload = function(){<!--  w ww . ja  v a 2  s  .c  o  m-->
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                
                // 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 World!", 0, 0);
            };
        </script>
    </head>
    <body>
        <canvas id="myCanvas" width="600" height="250" style="border:1px solid black;">
        </canvas>
    </body>
</html>

The code above is rendered as follows: