From b685e180d04202c704ec32c83ada64ed57067856 Mon Sep 17 00:00:00 2001 From: Ilias Ismanalijev Date: Wed, 3 Apr 2019 01:22:22 +0200 Subject: [PATCH] moveToCenterOfElement, moveToCenterOfBounds --- index.d.ts | 2 ++ index.js | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/index.d.ts b/index.d.ts index 2534d65..e5db546 100644 --- a/index.d.ts +++ b/index.d.ts @@ -27,6 +27,8 @@ declare module "panzoom" { dispose: () => void; moveBy: (dx: number, dy: number, smooth: boolean) => void; moveTo: (x: number, y: number) => void; + moveToCenterOfElement: (element: Element, xOffset: number = 0, yOffset: number = 0) => void; + moveToCenterOfBounds: (bounds: DOMRect, xOffset: number = 0, yOffset: number = 0) => void; centerOn: (ui: any) => void; zoomTo: (clientX: number, clientY: number, scaleMultiplier: number) => void; zoomAbs: (clientX: number, clientY: number, zoomLevel: number) => void; diff --git a/index.js b/index.js index 87d711e..471817e 100644 --- a/index.js +++ b/index.js @@ -111,6 +111,8 @@ function createPanZoom(domElement, options) { moveTo: moveTo, centerOn: centerOn, zoomTo: publicZoomTo, + moveToCenterOfElement: moveToCenterOfElement, + moveToCenterOfBounds: moveToCenterOfBounds, zoomAbs: zoomAbs, smoothZoom: smoothZoom, getTransform: getTransformModel, @@ -741,6 +743,45 @@ function createPanZoom(domElement, options) { return zoomByRatio(clientX, clientY, scaleMultiplier) } + + /** + * Calculate the center of a given bounding rectangle's position from our container viewpoint + * @param {DOMRect} elemBounds + */ + function getCenterOfBounds(elemBounds) { + const containerBounds = owner.getBoundingClientRect() + + const centerX = -elemBounds.left + (((containerBounds.width / 2) - (elemBounds.width / 2))) + const centerY = -elemBounds.top + (((containerBounds.height / 2) - (elemBounds.height / 2)) + containerBounds.top) + + const newX = transform.x + centerX + const newY = transform.y + centerY + + return { x: newX, y: newY } + } + + /** + * Moves the view to the center of element + * @param {Element} element get the center of this HTML element + * @param {Number} xOffset offset x pixels from center horizontally + * @param {Number} yOffset offset y pixels from center vertically + */ + function moveToCenterOfElement(element, xOffset = 0, yOffset = 0) { + const bounds = element.getBoundingClientRect() + moveToCenterOfBounds(bounds, xOffset, yOffset) + } + + /** + * Moves the view to the center of the bounding rectangle + * @param {DOMRect} bounds + * @param {Number} xOffset offset x pixels from center horizontally + * @param {Number} yOffset offset y pixels from center vertically + */ + function moveToCenterOfBounds(bounds, xOffset = 0, yOffset = 0) { + const { x, y } = getCenterOfBounds(bounds) + moveTo(x + xOffset, y + yOffset) + } + function cancelZoomAnimation() { if (zoomToAnimation) { zoomToAnimation.cancel()