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.

  • http://hybernaut.com hybernaut

    Why not make this a proxy? Duplicate statements sure seem error-prone.

    • http://www.simonsarris.com 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 :P

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

  • http://hybernaut.com hybernaut

    OK, that makes sense. I will experiment with making this into a proxy and share what I’ve learned.

    Thanks!

  • 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.

  • 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);

  • AlexXsWx

    Thanks, helped alot!

  • kamishi

    Thank you for this class, very useful !