Zoom Canvas around Mouse Cursor
Zooming images using the scroll wheel is a common feature in web applications. In this case, the goal is to mimic the behavior of Google Maps, where zooming occurs around the mouse cursor.
Problem
The challenge lies in calculating the necessary movements to achieve this zoom effect. Given the image's top-left corner coordinates, width, height, and the mouse cursor's x and y coordinates relative to the canvas center, how do we determine the zoom transformations?
Solution
The solution involves three steps using the canvas context:
The following JavaScript code implements these steps:
ctx.translate(pt.x,pt.y); ctx.scale(factor,factor); ctx.translate(-pt.x,-pt.y);
Demo and Additional Notes
A working demonstration of this technique can be found here: http://phrogz.net/tmp/canvas_zoom_to_cursor.html
The demo supports dragging, click-to-zoom-in, shift-click-to-zoom-out, and scroll wheel zoom. It's worth noting that Safari exhibits faster zooming behavior than other browsers like Chrome and Firefox.
The above is the detailed content of How to Mimic Google Maps Zoom Behavior with Canvas: Zooming Around the Mouse Cursor?. For more information, please follow other related articles on the PHP Chinese website!