Zooming a Canvas to the Mouse Cursor
When creating an interactive HTML5
Problem:
How can we zoom a canvas relative to the cursor's position, similar to Google Maps?
Variables Available:
- Image coordinates (x, y)
- Image dimensions (width, height)
- Cursor coordinates relative to the canvas center (cursor_x, cursor_y)
Solution:
-
Translate the Canvas: Shift the canvas context based on the cursor's offset, allowing zooming around the cursor.
-
Scale the Canvas: Adjust the scale factor to zoom in or out.
-
Translate Back: Return the canvas context to its original position, compensating for the initial translation.
Here's the code snippet:
<code class="javascript">ctx.translate(cursor_x, cursor_y);
ctx.scale(factor, factor);
ctx.translate(-cursor_x, -cursor_y);</code>
Copy after login
Example in Action:
Visit http://phrogz.net/tmp/canvas_zoom_to_cursor.html for a live demonstration. It supports dragging and zooming with mouse clicks and the scroll wheel.
Note:
- For accurate zooming, transform the cursor position from screen space to the transformed canvas context.
- Currently, Safari's zooming behavior differs from other browsers, resulting in excessive zooming.
The above is the detailed content of How to Zoom a Canvas to the Mouse Cursor Position in HTML5?. For more information, please follow other related articles on the PHP Chinese website!