How to create a transformation matrix with HTML5?

In the following article, we are going to learn about how to create a transformation matrix with HTML5. HTML5 canvas provides methods that allow modifications directly to the transformation matrix. The transformation matrix must initially be the identity transform. It may then be adjusted using the transformation methods.

The transformation matrix is a 2D mathematical representation that defines how points in a coordinate system are mapped to new positions. In canvas context, it enables scaling, rotation, translation, and skewing of drawn elements.

2D Transformation Matrix ? a c tx ? ? b d ty ? ? 0 0 1 ? a, d: scaling b, c: skewing/rotation tx, ty: translation (horizontal, vertical) Identity Matrix: [1, 0, 0, 1, 0, 0]

Using the transform() Method

The transformation matrix of the current context can be changed using the transform() method. In other words, transform() method lets you scale, rotate, move, and skew the current context.

Note − Only drawings that are created after the transform() method is called will be impacted by the transformation.

Syntax

Following is the syntax of the transform() method −

ctx.transform(a, b, c, d, tx, ty)

Parameters

The transform() method accepts six parameters −

  • a − Horizontal scaling factor

  • b − Vertical skewing factor

  • c − Horizontal skewing factor

  • d − Vertical scaling factor

  • tx − Horizontal translation (movement)

  • ty − Vertical translation (movement)

Using the setTransform() Method

The setTransform() method resets the current transform to the identity matrix, then calls the transform() function with the same arguments. This method replaces the current transformation matrix rather than multiplying it.

Syntax

Following is the syntax for the setTransform() method −

ctx.setTransform(a, b, c, d, tx, ty)

Let's look into the following examples for better understanding of transformation matrix with HTML5 −

Example 1 − Basic Rectangle Transformation

In the following example, we are generating a rotated rectangle using the transform() method −

<!DOCTYPE html>
<html>
<head>
   <title>Basic Transform Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <canvas id="tutorial" width="300" height="300" style="border: 1px solid #ccc;"></canvas>
   <script>
      var canvas = document.getElementById("tutorial");
      if (canvas.getContext) {
         var ctx = canvas.getContext('2d');
         
         // Draw original rectangle
         ctx.strokeStyle = "blue";
         ctx.lineWidth = 2;
         ctx.strokeRect(50, 50, 100, 60);
         
         // Apply transformation (rotate 30 degrees)
         var angle = 30 * Math.PI / 180;
         var cos = Math.cos(angle);
         var sin = Math.sin(angle);
         
         ctx.transform(cos, sin, -sin, cos, 100, 50);
         ctx.strokeStyle = "red";
         ctx.strokeRect(0, 0, 100, 60);
      }
   </script>
</body>
</html>

The output displays the original blue rectangle and a rotated red rectangle −

Blue rectangle (original position)
Red rectangle (rotated 30 degrees)

Example 2 − Multiple Transformations with Gradual Rotation

In the following example, we are using both transform() and setTransform() methods to create a spiral pattern −

<!DOCTYPE html>
<html>
<head>
   <title>Multiple Transformations</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <canvas id="mycanvas" width="400" height="400" style="border: 1px solid #ccc;"></canvas>
   <script>
      function drawShape() {
         var canvas = document.getElementById('mycanvas');
         if (canvas.getContext) {
            var ctx = canvas.getContext('2d');
            var sin = Math.sin(Math.PI / 6);
            var cos = Math.cos(Math.PI / 6);
            
            ctx.translate(200, 200);
            var c = 0;
            
            for (var i = 0; i <= 12; i++) {
               c = Math.floor(255 / 12 * i);
               ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")";
               ctx.fillRect(0, 0, 80, 80);
               ctx.transform(cos, sin, -sin, cos, 0, 0);
            }
            
            // Reset and draw overlay
            ctx.setTransform(-1, 0, 0, 1, 200, 200);
            ctx.fillStyle = "rgba(100, 150, 255, 0.6)";
            ctx.fillRect(25, 25, 80, 80);
         }
      }
      drawShape();
   </script>
</body>
</html>

The output shows a spiral pattern of rectangles with gradually changing colors and a blue overlay rectangle −

Spiral pattern of gray rectangles (rotating 30 degrees each)
Blue semi-transparent overlay rectangle

Example 3 − Creating Geometric Patterns

In the following example, we are creating a geometric pattern using rotation transformations −

<!DOCTYPE html>
<html>
<head>
   <title>Geometric Pattern</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 10px;">
   <canvas id="mytutorial" width="400" height="400" style="border: 1px solid #ccc;"></canvas>
   <script>
      function tutorial() {
         const ctx = document.getElementById('mytutorial').getContext('2d');
         const sin = Math.sin(Math.PI / 6);
         const cos = Math.cos(Math.PI / 6);
         
         ctx.translate(200, 200);
         let c = 0;
         
         for (let i = 0; i <= 10; i++) {
            c = Math.floor(255 / 12 * i);
            ctx.fillStyle = 'rgb(88, 214, 141)';
            ctx.fillRect(0, 0, 120, 15);
            ctx.transform(cos, sin, -sin, cos, 0, 0);
         }
         
         ctx.setTransform(-1, 0, 0, 1, 200, 200);
         ctx.fillStyle = 'rgba(211, 84, 0, 0.7)';
         ctx.fillRect(-50, -50, 100, 100);
      }
      tutorial();
   </script>
</body>
</html>

The output displays a star-like pattern of green rectangles with an orange square in the center −

Star pattern of green rectangles (11 rectangles rotated)
Orange semi-transparent square in center

Comparison of Methods

Following table shows the key differences between transform() and setTransform() methods −

transform() Method setTransform() Method
Multiplies current transformation matrix with new values Resets to identity matrix then applies new transformation
Accumulates transformations (cumulative effect) Replaces current transformation completely
Useful for incremental changes Useful for absolute positioning
Multiple calls create compound transformations Each call starts fresh from identity matrix

Key Transformation Types

The transformation matrix can create different types of transformations −

  • Translationtransform(1, 0, 0, 1, tx, ty)

  • Scalingtransform(sx, 0, 0, sy, 0, 0)

  • Rotationtransform(cos(?), sin(?), -sin(?), cos(?), 0, 0)

  • Skewingtransform(1, tan(?y), tan(?x), 1, 0, 0)

Conclusion

HTML5 transformation matrices provide powerful control over canvas graphics through the transform() and setTransform() methods. The transform() method multiplies the current matrix for cumulative effects, while setTransform() resets to the identity matrix before applying new transformations. Understanding the six-parameter matrix structure enables precise control over scaling, rotation, translation, and skewing operations.

Updated on: 2026-03-16T21:38:53+05:30

380 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements