Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zoom Canvas to Mouse Cursor

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.

like image 546
S2am Avatar asked Mar 04 '11 05:03

S2am


People also ask

How do you get the mouse position on canvas?

To get real mouse position in canvas with JavaScript, we use the canvas getBoundingClientRect method. const getMousePos = (canvas, evt) => { const rect = canvas. getBoundingClientRect(); return { x: ((evt.

Can I use mouse wheel to zoom?

You can use the scroll wheel on your mouse to zoom in or out an image by pressing Alt (Mac: Option), and scrolling the wheel up or down.


1 Answers

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.

like image 177
Phrogz Avatar answered Sep 19 '22 17:09

Phrogz