make zooming zoom toward the mouse cursor

This commit is contained in:
りき萌 2025-06-26 16:34:01 +02:00
parent 385a691e3e
commit 2a783aba71
2 changed files with 22 additions and 2 deletions

View file

@ -433,12 +433,15 @@ class CanvasRenderer extends HTMLElement {
}
}
async #zoomingBehaviour() {
#zoomingBehaviour() {
this.addEventListener(
"wheel",
(event) => {
// TODO: Touchpad zoom
this.viewport.zoomIn(event.deltaY > 0 ? -1 : 1);
let windowSize = this.getWindowSize();
let ndcX = (event.clientX - this.clientLeft) / windowSize.width - 0.5;
let ndcY = (event.clientY - this.clientTop) / windowSize.height - 0.5;
this.viewport.zoomIntoPoint(event.deltaY > 0 ? -1 : 1, ndcX, ndcY, windowSize);
this.sendViewportUpdate();
this.dispatchEvent(new Event(".viewportUpdateEnd"));
},

View file

@ -14,6 +14,23 @@ export class Viewport {
this.zoomLevel = Math.max(-16, Math.min(20, this.zoomLevel));
}
// ndcX and ndcY are in -0.5 .. 0.5
// -0.5 -> (x) left or (y) top
// 0.5 -> (x) right or (y) bottom
// (0, 0) is the center of the screen
zoomIntoPoint(delta, ndcX, ndcY, windowSize) {
let beforePixelsX = (ndcX * windowSize.width) / this.zoom;
let beforePixelsY = (ndcY * windowSize.height) / this.zoom;
this.zoomIn(delta);
let afterPixelsX = (ndcX * windowSize.width) / this.zoom;
let afterPixelsY = (ndcY * windowSize.height) / this.zoom;
this.panX += beforePixelsX - afterPixelsX;
this.panY += beforePixelsY - afterPixelsY;
}
getVisibleRect(windowSize) {
let invZoom = 1 / this.zoom;
let width = windowSize.width * invZoom;