Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add zoomToFit feature #143

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ declare module "panzoom" {
) => void;
getTransform: () => Transform;
showRectangle: (rect: ClientRect) => void;
zoomToFit: (ui: any) => void;
pause: () => void;
resume: () => void;
isPaused: () => boolean;
Expand Down
57 changes: 41 additions & 16 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ function createPanZoom(domElement, options) {
smoothZoom: smoothZoom,
smoothZoomAbs: smoothZoomAbs,
showRectangle: showRectangle,
zoomToFit: zoomToFit,

pause: pause,
resume: resume,
Expand Down Expand Up @@ -444,26 +445,50 @@ function createPanZoom(domElement, options) {
internalMoveBy(x - transform.x, y - transform.y, true);
}

function internalMoveBy(dx, dy, smooth) {
if (!smooth) {
return moveBy(dx, dy);
}
function zoomToFit(ui) {
var parent = ui.ownerSVGElement
if (!parent) throw new Error('ui element is required to be within the scene')

if (moveByAnimation) moveByAnimation.cancel();
// TODO: should i use controller's screen CTM?
var clientRect = ui.getBoundingClientRect()
var cx = clientRect.left + clientRect.width/2
var cy = clientRect.top + clientRect.height/2

var from = { x: 0, y: 0 };
var to = { x: dx, y: dy };
var lastX = 0;
var lastY = 0;
var container = parent.getBoundingClientRect()
var dx = container.width/2 - cx
var dy = container.height/2 - cy

moveByAnimation = animate(from, to, {
step: function (v) {
moveBy(v.x - lastX, v.y - lastY);
var wx = window.innerWidth / 2;
var wy = window.innerHeight / 2;

lastX = v.x;
lastY = v.y;
}
});
var fitRatio = Math.min(wx / (clientRect.width / 2), wy / (clientRect.height / 2));

internalMoveBy(dx, dy, true, () => {smoothZoom(wx , wy, fitRatio)});

}

function internalMoveBy(dx, dy, smooth, done) {
if (!smooth) {
moveBy(dx, dy);
done();
} else {
if (moveByAnimation) moveByAnimation.cancel()

var from = { x: 0, y: 0 }
var to = { x: dx, y : dy }
var lastX = 0
var lastY = 0

moveByAnimation = animate(from, to, {
step: function(v) {
moveBy(v.x - lastX, v.y - lastY)

lastX = v.x
lastY = v.y
},
done: done
})
}
}

function scroll(x, y) {
Expand Down