Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-25 00:38:02
Original
230 people have browsed it

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!