I'm programming a HTML5 < canvas > project that involves zooming in and out of images using the scroll wheel. I want to zoom towards the cursor like google maps does but I'm completely lost on how to calculate the movements.
What I have: image x and y (top-left corner); image width and height; cursor x and y relative to the center of the canvas.
I hope, these JS libraries will help you: (HTML5, JS)
http://www.netzgesta.de/loupe/
https://github.com/akademy/CanvasZoom
https://github.com/zynga/scroller
As for me, I'm using loupe. It's awesome! For you the best case - scroller.
In short, you want to
translate()
the canvas context by your offset,scale()
it to zoom in or out, and thentranslate()
back by the opposite of the mouse offset. Note that you need to transform the cursor position from screen space into the transformed canvas context.Demo: http://phrogz.net/tmp/canvas_zoom_to_cursor.html
I've put up a full working example on my website for you to examine, supporting dragging, click to zoom in, shift-click to out, or scroll wheel up/down.
The only (current) issue is that Safari zooms too fast compared to Chrome or Firefox.
I took @Phrogz's answer as a basis and made a small library that enables canvas with dragging, zooming and rotating. Here is the example.
You can find more detailed examples and documentation on the project's page
I recently needed to archive same results as Phrogz had already done but instead of using
context.scale()
, I calculated each object size based on ratio.This is what I came up with. Logic behind it is very simple. Before scaling, I calculate point distance from edge in percentages and later adjust viewport to correct place.
It took me quite a while to come up with it, hope it saves someones time.