HTML5 Game - Shearing the canvas context

Introduction

The following code uses transform() method to create a custom shear transformation to skew the canvas context horizontally.

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 . j a v a 2  s  .c  om
                let rectWidth = 150;
                let rectHeight = 75;
                
                // shear matrix:
                //  1  sx  0              
                //  sy  1  0
                //  0  0  1  
                
                let sx = 0.75; // 0.75 horizontal shear
                let sy = 0; // no vertical shear
                // translate context to center of canvas
                context.translate(canvas.width / 2, canvas.height / 2);
                
                // apply custom transform
                context.transform(1, sy, sx, 1, 0, 0);
                
                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 shear the canvas context, use the transform() method with the following parameters:

context.transform(1,sy,sx,1,0,0); 

The larger value of sx, the greater the context is sheared horizontally.

The larger value of sy, the greater the context is sheared vertically.

Related Topic