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.
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.
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With