Home  >  Article  >  Web Front-end  >  How do you Zoom a Canvas Context to the Mouse Cursor in HTML5?

How do you Zoom a Canvas Context to the Mouse Cursor in HTML5?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 18:47:04564browse

How do you Zoom a Canvas Context to the Mouse Cursor in HTML5?

Zooming the Canvas Context to the Mouse Cursor

In a HTML5 canvas project involving image zooming using the scroll wheel, you may encounter the challenge of zooming toward the cursor, similar to the functionality in Google Maps. To achieve this effect, a series of calculations are necessary.

Calculating the Movements

  1. Determining the Canvas Context Transformation:

    • Translate the canvas context by the cursor's offset (pt.x, pt.y).
    • Scale the context using a zoom factor (factor).
    • Translate the context back by the negative of the cursor's offset.
    <code class="js">ctx.translate(pt.x, pt.y);
    ctx.scale(factor, factor);
    ctx.translate(-pt.x, -pt.y);</code>
  2. Transforming the Cursor Position:

    • The cursor's screen space coordinates need to be converted into the transformed canvas context coordinates for accurate zooming.

Example Demonstration

Visit the following link for a working example that includes:

  • Canvas image zooming to the cursor
  • Dragging support
  • Click to zoom in, Shift-click to zoom out
  • Scroll wheel zooming

Demo: http://phrogz.net/tmp/canvas_zoom_to_cursor.html

Note: In Safari, the zooming behavior may differ from Chrome or Firefox.

The above is the detailed content of How do you Zoom a Canvas Context to the Mouse Cursor in HTML5?. 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