HTML Canvas transform() shear canvas context

Introduction

To shear the canvas context, we can apply the following transformation matrix:

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

View in separate window

<html>
    <head>
        <script>   
            window.onload = function(){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");
                /*from  w  w w  . ja v  a  2  s. c o m*/
                var rectWidth = 150;
                var rectHeight = 75;
                
                // shear matrix:
                //  1  sx  0              
                //  sy  1  0
                //  0  0  1  
                
                var sx = 0.75; // 0.75 horizontal shear
                var 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>



PreviousNext

Related