HTML5 Game - Applying a Transform Matrix

Introduction

Canvas function setTransform() can apply multiple effects to objects.

The function uses a set of parameters, called the transform matrix, to calculate Canvas adjustments:

setTransform(scaleX, skewY, skewX, scaleY, translateX, translateY)

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>

<head>
    <script>
        window.onload = function() {
            canvas = document.getElementById("canvasArea");
            context = canvas.getContext("2d");

            context.fillStyle = "silver";
            context.fillRect(0, 0, canvas.width, canvas.height);

            //sc:scale  
            //sk:skew  
            //tr:translate
            //X:horizontal axis    
            //Y:vertical axis
            //       scX  scY  skX  skY  trX  trY  color
            drawRect(1.0, 1.0, 0.0, 0.0, 25, 25, "blue");
            drawRect(1.0, 1.0, 0.2, 0.0, 125, 25, "green");
            drawRect(1.0, 1.0, 0.0, 0.2, 225, 25, "red");
            drawRect(1.0, 1.0, 0.2, 0.2, 325, 25, "yellow");
            drawRect(1.2, 1.0, 0.0, 0.0, 25, 110, "purple");
            drawRect(1.0, 1.2, 0.0, 0.0, 125, 110, "aqua");
            drawRect(1.2, 1.2, 0.2, 0.2, 225, 110, "orange");
            drawRect(1.3, 1.3, -.2, -.2, 325, 110, "pink");
        }/* w ww. j a  v a  2 s  .  co  m*/
        //DRAW rectangle function.
        function drawRect(scaleX, scaleY,
            skewX, skewY,
            translateX, translateY, color) {
            //ATTRIBUTES & VARIABLES.
            let width = 60;
            let height = 40;
            context.shadowOffsetX = 4;
            context.shadowOffsetY = 4;
            context.shadowBlur = 5;
            context.shadowColor = "gray";
            context.fillStyle = color;

            context.setTransform(scaleX, skewY,
                skewX, scaleY,
                translateX, translateY);

            context.fillRect(0, 0, width, height);
        }
    </script>
</head>

<body>

    <div style="width:425px;   height:200px;
                 margin:0 auto; padding:5px;">
        <canvas id="canvasArea" width="425" height="200" style="border:2px solid black">
            You're browser doesn't currently support HTML5 Canvas.
        </canvas>
    </div>
</body>

</html>

Related Topic