Skip to content
Advertisement

Javascript pseudo-zoom around mouse position in canvas

I would like to “zoom” (mouse wheel) a grid I have, around the mouse position in canvas (like Desmos does). By zooming, I mean redrawing the lines inside the canvas to look like a zoom effect, NOT performing an actual zoom. And I would like to only use vanilla javascript and no libraries (so that I can learn).

At this point, I set up a very basic magnification effect that only multiplies the distance between the gridlines, based on the mouse wheel values.

JavaScript
JavaScript
JavaScript

This works fine but, as expected, it magnifies the grid from the top left corner not from the mouse position.

So, I thought about detecting the mouse position and then modifying all the “moveTo” and “lineTo” parts. The goal would be to offset the magnified grid so that everything is displaced except the 2 lines intersecting the current mouse coordinates.

For instance, it feels to me that instead of this:

JavaScript

I should have something like this:

JavaScript

But after hours of trials and errors, I’m stuck. So, any help would be appreciated.

FYI: I already coded a functional panning system that took me days to achieve (that I stripped from the code here for clarity), so I would like to keep most of the logic I have so far, if possible. Unless my code is total nonsense or has performance issues, of course.

Thank you.

Advertisement

Answer

You’re already tracking the mouse position in pixels. If you transform the mouse position to the coordinate system of your grid, you can define which grid cell it’s hovering.

After zooming in, you can again calculate the mouse’s coordinate. When zooming in around another center point, you’ll see the coordinate shift.

You can undo that shift by translating the grid’s center in the opposite direction.

Here’s the main part of it:

JavaScript

To make this easier to work with, I introduced a grid.centerX and .centerY. I updated your draw method to take the center in to account (and kind of butchered it along the way, but I think you’ll manage to improve that a bit).

Here’s the complete example:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement