Chris
Chris

Reputation: 27394

Pan & Zoom canvas issue when canvas is resized

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.

Upvotes: 0

Views: 1664

Answers (2)

CarbonDonuts
CarbonDonuts

Reputation: 65

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.

Upvotes: 1

vogdb
vogdb

Reputation: 4829

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.

Upvotes: 0

Related Questions