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();
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:


Or the shorter:

var t = new Transform();

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.

7 thoughts on “A transformation class for Canvas to keep track of the transformation matrix

    1. simonsarris

      I considered doing that but wanted to only release code that was very easy to understand and decoupled from anything. It isn’t hard to get there from here so making that is left as an exercise for the user 😛

      I actually never call rotate or translate or scale in one of my apps, I just use setTransform and this class all the time.

  1. Mtagliaf

    I was wondering if you might combine this tutorial and your object picking one.  Specifically, I’m looking for a way to transform an entire scene (it’s easier to draw my scene in the upper left corner and then rotate it), but then allow object picking as well.  I don’t even need object moving/resizing,  just object picking!  And my objects are all rectangles as well.  Let me know if you might be able to help out.

  2. Eric Higgins

    While it makes sense to be verbose in documentation, you could simplify the .setTransform call with the following:
    ctx.setTransform.apply(ctx, t.m);


Leave a Reply

Your email address will not be published. Required fields are marked *