Michael Levy

Paintings, photography, and other art

Adjusting Mouse Position After SVG Scale

After applying a css scale transformation to an SVG element, mouse positions within it were no longer accurate. The further they got from center the greater the inaccuracy became.

Mouse events are recorded from the top left, but zooms are based on a center point origin with negative values to the left and bottom. To scale the mouse position, they have to first be converted to a center point origin and translated back to a (top,left) origin .

Here is a process for converting mouse positions to positions within a zoomed SVG world.

Absolute Value: The value relative to the top left corner
Relative Value: The value relative to the center point used for zooming

Step 1: Find absolute value of mouse coordinates
Step 2: Convert mouse coordinates to their relative value at zoom(1.0)
Step 3: Find the inverse scale, the fraction to reverse the scale on zoomed SVG
Step 4: Scale relative values to screen values using inverse scale
Step 5: Convert inverted coordinates to absolute values

zoom-scaling-sketch