I'm having some issues with implementing a custom zoom.
I have most of the zoom functionality working, however, it zooms "around" the origin, in this case, the top-left corner of the grid. Instead, I want it to zoom in around the cursor.
The canvas is as big as the window (I'll be adding UI on top of the canvas, kinda like photoshop), and I'm drawing a grid to the canvas that is WIDTH x HEIGHT pixels large, "scaled up" by a factor of PIXEL_SIZE.
The important part of this, this event handler right here
const WIDTH = 32;
const HEIGHT = 24;
const PIXEL_SIZE = 10;
...
// controls how big the grid is
let scale = 1.5;
// controls where the grid is drawn,
// starts exactly in the middle of the screen
let originX = canvas.width / 2 - (WIDTH * PIXEL_SIZE * scale) / 2;
let originY = canvas.height / 2 - (HEIGHT * PIXEL_SIZE * scale) / 2;
function zoom(event) {
event.preventDefault();
const wheel = event.deltaY < 0 ? 1 : -1;
const z = Math.exp(wheel * 0.05);
scale *= z;
// this adjusts the scale just fine-ish
// however, the origin needs to move in relation
// to the cursor position
}
window.addEventListener("wheel", zoom, { passive: false });
I've tried a few things, but for some reason, my brain can't do the math at the moment. I've tried using ctx.translate and ctx.scale, but neither of them seems to do what I want to do (though I could be using them wrong).
Here's a JSFiddle with what I've got so far. If someone could take a look, that would be awesome.