HTML5 Game - Using a Transformation

Introduction

We can apply a transformation to the canvas.

It is then applied to any subsequent drawing operations.

The following table describes the transformation methods.

Name
Description
Returns
scale(<xScale>, <yScale>)

Scales the canvas by xScale in the x-axis and yScale
in the y-axis
void

rotate(<angle>)

Rotates the canvas clockwise around the point (0, 0)
by the specified number of radians.
void

translate(<x>, <y>)

Translates the canvas by x along the x-axis and y
along the y-axis.
void

transform(a, b, c, d, e, f)

Combines the existing transformation with the
matrix specified by the values a-f.
void

setTransform(a, b, c, d, e, f)

Replaces the existing transformation with the matrix
specified by the values a-f.
void

The transformations created by these methods only apply to subsequent drawing operations.

The following table shows how we can use the scale, rotate, and translate methods.

Demo

ResultView the demo in separate window

<!DOCTYPE HTML>
<html>
    <head>
        <title>Example</title>
        <style>
            canvas {border: thin solid black; margin: 4px;}
            body > * {float:left;}
        </style>
    </head>
    <body>
        <canvas id="canvas" width="400" height="200">
            Your browser doesn't support the <code>canvas</code> element
        </canvas>
        <script>
            let ctx = document.getElementById("canvas").getContext("2d");
                         //from ww  w  .  j  a v a 2  s .c o  m
            ctx.fillStyle = "lightgrey";
            ctx.strokeStyle = "black";
            ctx.lineWidth = 3;

            ctx.clearRect(0, 0, 300, 120);
            ctx.globalAlpha = 1.0;
            ctx.font = "100px sans-serif";
            ctx.fillText("Hello", 10, 100);
            ctx.strokeText("Hello", 10, 100);       
                            
            ctx.scale(1.3, 1.3);
            ctx.translate(100, -50);
            ctx.rotate(0.5);                            
                            
            ctx.fillStyle = "red";
            ctx.globalAlpha = 0.5;
            ctx.fillRect(100, 10, 150, 100);
            
            ctx.strokeRect(0, 0, 300, 200);
        </script>
    </body>
</html>

Related Topic