HTML5 Canvas Advanced: Part 1

222.png

I've already completed the basic parts of a HTML5 canvas in my previous series of HTML5 Canvas For Beginners in which I explained Basic Drawing, Curves & ShapesGradients, Images and Text. Now in this advanced series, we cover all the advanced topics of HTML5 canvas that includes transformation, composites, animation and so on.

HTML5 Canvas Transformations

In this article I explain basic transformations in the HTML5 Canvas. Transformation methods allow us to do various modifications to whatever we draw on the canvas. There are three main transformations:

  • Translation
  • Rotation
  • Scaling

Translation

In a HTML5 Canvas, the "translate()" transform method translates the canvas context. Translation means relocation, so it allows us to relocate the origin or (0,0) point, of the canvas context with only one method. In this method, we need to provide x and y co-ordinates. Let's draw a rectangle at the position(0,0). We need to use the "fillRect()" method :

            ctx.fillRect(0,0,150,100);

It will now draw a rectangle at the top-left corner of the canvas.

1-rectangleInCorner.PNG

Now, we will draw another rectangle at the same position and use the "translate()" method :

        ctx.translate(100, 100); 

        ctx.fillStyle = "#0000ff";

        ctx.fillRect(10, 10, 150, 100);

It will draw a new rectangle at the position(100,100). In simple words, we have drawn two rectangles in the preceding example at the same position, but the only twist is that we drew one rectangle before the translate( ) method and the other was drawn after it. The translate( ) method shifts both the co-ordinates of the canvas so that position(0,0) changes to position(100,100).

2-translate-coordinate(2).png

Example : Check Live Demo 

<body>

    <form id="form1" runat="server">

        <div>

            <input type="button" id="button" value="Translate" onclick="effect()" /><br />

            <canvas id="drawCanvas" width="400" height="320"></canvas>

 

            <script>

                var drawCanvas = document.getElementById('drawCanvas');

                var ctx = drawCanvas.getContext('2d');

                gridDraw(ctx, '#333', 15, 15);

 

                ctx.fillStyle = "#ff0000";

                ctx.fillRect(10, 10, 150, 100);

 

                var effect = function () {

                    ctx.translate(150, 100);

 

                    ctx.fillStyle = "#0000ff";

                    ctx.fillRect(10, 10, 150, 100);

                }

            </script>

        </div>

    </form>

</body>

Output

3-Translate-image.PNG

Scaling

In HTML5 Canvas, the "scale()" transform method scales the canvas context. As the name suggests, it resizes such that the size is the same as the grid. Let's see an example, in which we draw a rectangle:

6-scaling-coordinate.png

Now we need to use the "scale" transformation method to scale this rectangle. The scale() transformation method is used in a way similar to the translate() transformation method, so it is also applied before you draw the shape on the canvas context. It is really important to tell you that the properties of the scale method are multipliers of the x and y co-ordinates. It means that, if you use a scale of (3,3) then it would multiply the size of the canvas context by three, that makes it three times larger than the previous one.

In this example, we are going to increase the size of the rectangle by five times, so we need to use "scale(5,5)".

Example: Check Live Demo

<body>

    <form id="form1" runat="server">

        <div>

            <input type="button" id="button" value="Scale" onclick="effect()" /><br />

            <canvas id="drawCanvas" width="600" height="400"></canvas>

 

            <script>

                var drawCanvas = document.getElementById('drawCanvas');

                var ctx = drawCanvas.getContext('2d');

                gridDraw(ctx, '#333', 10, 10);

 

                ctx.fillStyle = "#ff0000";              // red color

                ctx.fillRect(10, 10, 100, 50);

 

                var effect = function () {

                    ctx.translate(10, 50);

                    ctx.scale(5, 5);

                    ctx.fillStyle = "#0000ff";          // blue color

                    ctx.fillRect(10, 10, 100, 50);    

                }

            </script>

        </div>

    </form>

</body>      

Output:

7-scale-coordinate.PNG

Rotation

In HTML5 Canvas, the "rotate()" transform method is used for rotation. Using the rotation method, you can rotate any shape drawn on the canvas. The rotate() method requires an angle as a parameter to rotate the shape. The value of the angle should be given in radians, not in degrees. Let's see a simple example :

       ctx.rotate(Math.PI / 4);

       ctx.fillStyle = "#0000ff";

       ctx.fillRect(100, 100, 150, 100);

Now, it will draw a rectangle at position (100,100) and rotates it. What ? This doesn't look correct:

4-rotationInCorner.PNG

Let's understand what happened in our example. It looks as if the rectangle is trying to go outside the browser window instead of rotating on its current position at (100,100). That happened because the rotate() method affects the entire 2D rendering context, like all other transformations.

Let's understand what happens with the co-ordinate system when you perform a 45 degree rotation:

5-rotate-coordinate(2).png

You can now see that the entire co-ordinate system or entire grid has rotated by 45 degrees from its previous point (0,0), instead of rectangle. To rotate the rectangle correctly, you need to use the "translate()" method to move the co-ordinate systems from the origin point (0,0) to the new position (150,200).

Example: Check Live Demo

<body>

    <form id="form1" runat="server">

        <div>

            <input type="button" id="button" value="Rotate" onclick="effect()" /><br />

            <canvas id="drawCanvas" width="500" height="400"></canvas>

 

            <script>

                var drawCanvas = document.getElementById('drawCanvas');

                var ctx = drawCanvas.getContext('2d');

                gridDraw(ctx, '#333', 10, 10);

 

                ctx.fillStyle = "#ff0000";              // red color

                ctx.fillRect(30, 30, 150, 100);

 

                var effect = function () {

                    ctx.translate(150, 200);            // Translate to centre of rectangle 

                    ctx.rotate(Math.PI / 4);            // Rotate 45 degrees (in radians)

                    ctx.fillStyle = "#0000ff";          // blue color

                    ctx.fillRect(-40, -40, 150, 100);   // Centre at the rotation point 

                }

            </script>

        </div>

    </form>

</body>

 

Output: 


rotateFinal.PNG

The rotation transformation really is toughest one to understand completely. Always keep in mind that whenever you use transformation, it performs on the entire 2D rendering context, and if you want to use the rotate() method then you should use the translate() method before it.

In the next part, we will learn all about the advanced part of transformation.

Up Next
    Ebook Download
    View all
    Learn
    View all