Home  >  Article  >  Web Front-end  >  How to Mimic Google Maps Zoom Behavior with Canvas: Zooming Around the Mouse Cursor?

How to Mimic Google Maps Zoom Behavior with Canvas: Zooming Around the Mouse Cursor?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-25 00:38:02231browse

How to Mimic Google Maps Zoom Behavior with Canvas: Zooming Around the Mouse Cursor?

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:

  1. Translate: Move the context origin to the mouse cursor's position to center the zoom around it.
  2. Scale: Zoom in or out by the desired factor.
  3. Translate (reversed): Move the origin back to its original position.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn