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.


In short, you want to translate() the canvas context by your offset, scale() it to zoom in or out, and then translate() 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.

ctx.translate(pt.x,pt.y);
ctx.scale(factor,factor);
ctx.translate(-pt.x,-pt.y);

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 hope, these JS libraries will help you: (HTML5, JS)

  1. Loupe

http://www.netzgesta.de/loupe/

  1. CanvasZoom

https://github.com/akademy/CanvasZoom

  1. Scroller

https://github.com/zynga/scroller

As for me, I'm using loupe. It's awesome! For you the best case - scroller.