Zoom on cursor | Issue #940 (#2319)

This commit is contained in:
João Forja 2020-11-04 17:49:15 +00:00 committed by GitHub
parent facde7ace0
commit 566e6a5ede
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 912 additions and 357 deletions

View file

@ -1,4 +1,4 @@
import { AppState, FlooredNumber } from "../types";
import { AppState, FlooredNumber, PointerCoords, Zoom } from "../types";
import { ExcalidrawElement } from "../element/types";
import { getCommonBounds, getClosestElementBounds } from "../element";
@ -19,14 +19,10 @@ function isOutsideViewPort(
const { x: viewportX1, y: viewportY1 } = sceneCoordsToViewportCoords(
{ sceneX: x1, sceneY: y1 },
appState,
canvas,
window.devicePixelRatio,
);
const { x: viewportX2, y: viewportY2 } = sceneCoordsToViewportCoords(
{ sceneX: x2, sceneY: y2 },
appState,
canvas,
window.devicePixelRatio,
);
return (
viewportX2 - viewportX1 > appState.width ||
@ -34,6 +30,29 @@ function isOutsideViewPort(
);
}
export const centerScrollOn = ({
scenePoint,
viewportDimensions,
zoom,
}: {
scenePoint: PointerCoords;
viewportDimensions: { height: number; width: number };
zoom: Zoom;
}) => {
return {
scrollX: normalizeScroll(
(viewportDimensions.width / 2) * (1 / zoom.value) -
scenePoint.x -
zoom.translation.x * (1 / zoom.value),
),
scrollY: normalizeScroll(
(viewportDimensions.height / 2) * (1 / zoom.value) -
scenePoint.y -
zoom.translation.y * (1 / zoom.value),
),
};
};
export const calculateScrollCenter = (
elements: readonly ExcalidrawElement[],
appState: AppState,
@ -45,7 +64,6 @@ export const calculateScrollCenter = (
scrollY: normalizeScroll(0),
};
}
const scale = window.devicePixelRatio;
let [x1, y1, x2, y2] = getCommonBounds(elements);
if (isOutsideViewPort(appState, canvas, [x1, y1, x2, y2])) {
@ -54,8 +72,6 @@ export const calculateScrollCenter = (
viewportCoordsToSceneCoords(
{ clientX: appState.scrollX, clientY: appState.scrollY },
appState,
canvas,
scale,
),
);
}
@ -63,8 +79,9 @@ export const calculateScrollCenter = (
const centerX = (x1 + x2) / 2;
const centerY = (y1 + y2) / 2;
return {
scrollX: normalizeScroll(appState.width / 2 - centerX),
scrollY: normalizeScroll(appState.height / 2 - centerY),
};
return centerScrollOn({
scenePoint: { x: centerX, y: centerY },
viewportDimensions: { width: appState.width, height: appState.height },
zoom: appState.zoom,
});
};