Falcon80 Logo
Using the transform matrix on canvas

Until now, we have been dealing with transformations that are intuitive and does not need a matrix-level understanding of the transformation. However, in order to use the Transformation() method, it is important to have a basic understanding of matrix manipulation. So here we go.

Matrix Manipulation

If you are working with 2-D, you can basically represent any point on the canvas in the matrix form. For example, if you have a point (x,y), it can be represented as:

Suppose we want to translate/move this point (x,y) to another location say (x1,y1), this change in location can be achieved by adding dx to the x coordinate and dy to the y coordinate where dx = x1-x and dy = y1-y. So we will essentially be doing a matrix addition as follows:

While points represented as 2 X 1 matrices work for simple transformations, complex transformations may require that they be represented as homogeneous coordinates. What this means is that instead of representing points as 2 X 1 matrices, we will be representing them as 3 X 1 matrices as follows.

In this case, the translation matrix would be written as

and multiplied with the current transformation matrix to get the change of location instead of performing matrix addition.

So, the result after translation would be

The transform() method

The transform() method allows you to apply any transformation to the current matrix. So you can use it to do scaling, rotating, translation as well as many other complex transformations. The method takes six parameters:

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

where a,b,c,d,e, and f form the following transformation matrix:

The current transformation matrix gets replaced by the product of the current transformation matrix and the matrix provided in the transform() method.

  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {

var ctx = canvas.getContext("2d");
//Load a new image and draw it at 25,0)
var flower = new Image();
flower.src = "flower.png";

// Let's do a translation and move the image 200 pixels in the x-direction and 20 pixels // in the y-direction
var dx = 200;
var dy = 20;

  <title>Translating an image on canvas </title>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
Try Code