Skip to content

Commit

Permalink
chore: refactor zoom calculation from viewport
Browse files Browse the repository at this point in the history
  • Loading branch information
micahg committed Aug 25, 2024
1 parent fa53643 commit e40c77f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 24 deletions.
26 changes: 2 additions & 24 deletions packages/mui/src/utils/contentworker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
scalePoints,
translatePoints,
copyRect,
zoomFromViewport,
} from "./geometry";
import { Rect } from "@micahg/tbltp-common";

Expand Down Expand Up @@ -177,30 +178,7 @@ function adjustZoomFromViewport() {
// set our viewport to the initial value requested
copyRect(_img_orig, _img);

// unrotate canvas
const [cW, cH] = rotatedWidthAndHeight(
-_angle,
_canvas.width,
_canvas.height,
);
const zW = _img.width / cW;
const zH = _img.height / cH;

// set zoom and offset x or y to compensate for viewport
// aspect ratios that are different from the screen
if (zH > zW) {
_zoom = zH;
const adj = cW * _zoom;
if (adj < _fullRotW) {
_img.x -= (adj - _img.width) / 2;
}
} else {
_zoom = zW;
const adj = cH * _zoom;
if (adj < _fullRotH) {
_img.y -= (adj - _img.height) / 2;
}
}
_zoom = zoomFromViewport(_angle, _canvas.width, _canvas.height, _img);
}

/**
Expand Down
26 changes: 26 additions & 0 deletions packages/mui/src/utils/geometry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,32 @@ export function translatePoints(points: Point[], x: number, y: number) {
return tPoints;
}

/**
* Given a desired viewport, set our current viewport accordingly, set the zoom,
* and then center the request viewport within our screen, extending its short
* side to fit our screen.
*
* This is used when the remote client is told which region to display, rather
* than in the editor, where (iirc) you calculate the viewpoint given a point,
* a zoom level and the canvas size.
*/
export function zoomFromViewport(
angle: number,
containerWidth: number,
containerHeight: number,
img: Rect,
) {
// un-rotate canvas
const [cW, cH] = rotatedWidthAndHeight(
-angle,
containerWidth,
containerHeight,
);
const zW = img.width / cW;
const zH = img.height / cH;
return Math.max(zW, zH);
}

/**
* rotate and fill viewport to fit screen/window/canvas
* @param screen screen [width, height]
Expand Down

0 comments on commit e40c77f

Please sign in to comment.