A transformation class for Canvas to keep track of the transformation matrix

I’m writing a book on HTML5, including Canvas! Click here for more information.

The HTML5 Canvas does not have a method for getting the current transformation matrix. For some applications, keeping track of the current transformation matrix would be a nice feature to have.

I’ve made this easier by creating a simple Transform class for use with Canvas. You can have a look at it here.

It has all of the Canvas equivalents, and can be used alongside canvas to record the matrix state or can be used instead of and then applied to the canvas.

In other words, a start-to-finish use of the Transform would be like this:

var t = new Transform();
t.rotate(5);
var m = t.m;
ctx.setTransform(m[0], m[1], m[2], m[3], m[4], m[5]);

Which will do the exact same thing as this:

ctx.rotate(5);

Or the shorter:

var t = new Transform();
t.rotate(5);
ctx.rotate(5);

But of course allow you to keep track of it!

If you wanted, you could easily call the class to take a context and always do the operations when it is called.