1

I have some confusion of how to implement zoom in point in HTML canvas. I have read all the other posts here about it, but there is an issue that is still not clear to me.

So, I fully understand the concept of zooming into point - first translate the desired zooming center to the origin, scale in/out, translate back. So if I wish to zoom around point p1 by factor k1 and then again around point p2 by factor k2, I will first translate to origin with transformation T1 = T(-p1.x, -p1.y), zoom with S1(k1) by factor k1 and translate back with T1' = T(p1.x, p1.y).

Then again will do the same around p2: translate to origin with T2 = T(-p2.x, -p2.y), zoom with S2(k2) by factor k2 and translate back with T2' = T(p2.x, p2.y). So those two zoom actions will transform a given point q to q' with the following:

q' = (T2' * S2 * T2) * (T1' * S1 * T1) * q

Now suppose I want to implement it with HTML canvas. I would expect that the following lines will accomplish it:

// First zoom around p1
context.translate(-p1.x, -p1.y); // T1 - translate to origin
context.scale(k1,k1); // S1 - scale
context.translate(p1.x, p1.y); // T1' - translate back

// Then zoom around p2
context.translate(-p2.x, -p2.y); // T2 - translate to origin
context.scale(k2,k2); // S2 - scale
context.translate(p2.x, p2.y); // T2' - translate back

However, since the HTML canvas post-multiply transformations, this piece of code will be interpreted as the following:

q' = (T1 * S1 * T1') * (T2 * S2 * T2') * q

This obviously won't yield what I want - the multiplication order is not as I wanted.

Why is it like that? What intuition I'm missing? My intuition for when I read this piece of code top to bottom is that the transformations should be pre-multiplied.

Thanks!

Nor
  • 11
  • 2
  • This post may be helpful: http://stackoverflow.com/questions/27339747/zoom-and-pan-in-animated-html5-canvas/27340533#27340533 – markE May 20 '15 at 21:19
  • "the multiplication order is not as I wanted", with multiplication, order doesn't matter. –  May 20 '15 at 22:54
  • using save() and restore() is a much simpler way of using different transforms. – GameAlchemist May 21 '15 at 08:16
  • @K3N : unfortunately for us all, no, matrix multiplication isn't commutative. – GameAlchemist May 21 '15 at 23:24
  • @GameAlchemist a (transformation) matrix involves addition as well. I was nevertheless referring to the formula in the question which only do multiplications so OP didn't have to waste time experiment changing order around. –  May 22 '15 at 01:29
  • A transformation matrix is a matrix. With matrix multiplication, order does matter. And the formula corresponding to the code should read q' = (T2' * S2 * T2) * (T1' * S1 * T1) * q – GameAlchemist May 22 '15 at 03:47

0 Answers0