I've been playing with HTML canvas transforms and have had to brush up on how transforms work. It's really just matrices math; eigenvalues, dot products, triple products etc. I should know this stuff pretty well as it was extensively covered in my Engineering undergrad studies and I've previously played with them to do 2D and 3D computer graphics.

However when I have the choice between understanding the math and just typing a few lines and seeing the effect, I often just do the latter. I know, I really need to get past that.

I seemed to be able to get transforms to do what I wanted them to do, but until I got them right I was finding they often didn't do what I expected they would.

So I decided I would explore it a bit using the transforms themselves, but I'm not sure if I've cleared up my understanding. I probably should have just studied the math and written an asteroids game.

Rotate on axis then centre

The example transforms I looked at was rotating a square drawn from (0,0) to (50,50) about its centre, then moving it to (50,50).

This is basically a series of transforms, where the order is important. If this makes perfect sense you can probably just check out the animations and hopefully leave a comment explaining what is going on more clearly than I have.

translate(50,50)
rotate(Math.PI/4)
translate(-25,-25)
draw(..)

My brain thought this looked a bit backward, and it wasn't helped when I tried to animate applying the transforms one by one. Sure it worked out, but not as I expected it too.

Yo, this demo requires canvas. Best viewed with a browser that supports it.

Click to start animation

I noticed this would look as I expected if I animated the transforms in reverse order while still applying them in the correct order.

Yo, this demo requires canvas. Best viewed with a browser that supports it.

Click to start animation

The previous animations illustrate what was bothering me, but they are not exactly what I wanted to show in the first place. The transforms apply to the canvas and the square is drawn at (0,0) after the transforms are applied.

To show that we need to invert everything (kind of, more on that in another post maybe) and move the axis instead.

Yo, this demo requires canvas. Best viewed with a browser that supports it.

Click to start animation

You would think by now I would have started to understand all this but I haven't really. What is more annoying is I wanted to make a demo in which a user could add arbitrary transforms one at time, but the only way I could animate that nicely is if I asked for the transforms in reverse order. Perhaps that is the way to think about it.

Anyway I suck, hopefully a commenter can explain this more clearly than I have. Until then I hope this helps you grok how transforms work, but the real lesson here is know ye' math. Stay at school kids.

Comments