HTML Canvas Context scale

Introduction

To scale the canvas context, we can simply use the scale transform:

context.scale(sx,sy); 

View in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                /*from w  ww.  j a va2 s .com*/
                var rectWidth = 150;
                var rectHeight = 75;
                
                // translate context to center of canvas
                context.translate(canvas.width / 2, canvas.height / 2);
                
                // scale down canvas height by half
                context.scale(1, 0.5);
                
                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