简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM