0

I have used the code I found on this stackoverflow answer (live demo here) to implement pan & zoom on my canvas. This works great but I have an issue.

My entire page is the canvas so when the browser is resized the canvas is also resized. Without any code this just makes the canvas stretch which looks horrible. If I setup some jQuery to resize the canvas when the browser is resized then I get really weird panning issues later on.

I'm not sure what variables to update or how to update them properly to allow pan and zoom to continue functioning after the canvas is resized.

Community
  • 1
  • 1
Chris
  • 26,744
  • 48
  • 193
  • 345

2 Answers2

1

Hey @Chris this question is a bit old, but I had the same question myself and this is what I did:

window.addEventListener('resize', function() { 
    var transform = context.getTransform();
    context.setTranslate( transform.e, transform.f);
    context.setScale( transform.d, transform.d );
} , false);

in @Phrogz 's function trackTransforms(ctx) i added two additional functions:

ctx.setTranslate = function( dx, dy ) {
    translate.call( ctx, dx, dy );
};
ctx.setScale = function(sx,sy) {
    scale.call( ctx, sx, sy );
};

Canvas resets itself, losing all the context changes, the nice pan zoom system made. This just tries to redo those changes based on the transformation.

  • Thanks for the answer, I won't have time to try it for a little while but certainly looks good! I'll come back when I have :) – Chris Jul 29 '15 at 11:17
0

In your case you need to do after zoom:

canvas.width = canvas.offsetWidth
canvas.height = canvas.offsetHeight

Also I made a library from the question you mentioned. It makes pan and zoom features much easier to use.

vogdb
  • 4,669
  • 3
  • 27
  • 29