HTML5 Game - Canvas Scale

Introduction

The HTML5 canvas API can scale the canvas context.

The following code scales down the height of the canvas context using the scale() method.

Demo

ResultView the demo in separate window

<html>
    <head>
        <script>
            window.onload = function(){
                let canvas = document.getElementById("myCanvas");
                let context = canvas.getContext("2d");
                // ww w  .ja  va 2 s .com
                let rectWidth = 150;
                let 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>

Note

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

context.scale(sx,sy); 

By default, the sx and sy parameters are normalized to 1 and 1.

The sx parameter corresponds to the horizontal scale.

The sy parameter corresponds to the vertical scale.

The code above shrunk the vertical context by 50% by setting the sy parameter to a value of 0.5.

Related Topics