ImageToSVG

How to Add Zoom and Pan to SVG

Implement smooth zoom and pan interactions on SVG graphics by dynamically updating the viewBox in response to scroll and drag events.

Preset:
Colors:
VTracer vectorization + SVGO optimizationPrivacy protected

Zooming by Manipulating viewBox

Zooming in SVG is achieved by shrinking the viewBox width and height (zooming in) or expanding them (zooming out), while adjusting the x and y offset to keep the zoom centered on the cursor or touch point rather than the top-left corner.

  • Shrink viewBox width/height to zoom in, expand to zoom out
  • Adjust viewBox x/y offset to keep zoom centered on cursor position
  • Clamp zoom level to reasonable min/max bounds for usability

Panning with Drag Events

Panning shifts the viewBox's x and y values in response to mouse or touch drag movement, calculated proportionally to the current zoom level so that panning speed feels consistent regardless of how zoomed in the user currently is.

  • Track drag delta and convert to viewBox coordinate space
  • Scale pan speed relative to current zoom level for consistent feel
  • Consider clamping pan bounds so users can't drag content fully off-screen

Frequently Asked Questions

Should I build zoom/pan from scratch or use a library?

For simple needs, manual viewBox manipulation works fine. For production features with pinch-zoom, momentum, and edge cases handled, a library like svg-pan-zoom saves significant development time.

How do I make zoom centered on the mouse cursor instead of the SVG origin?

Calculate the cursor's position within the current viewBox coordinate space, then adjust the new viewBox's x/y offset so that same point remains under the cursor after the zoom level changes.

Related guides

Ready to Convert Your Image to SVG?

Free online converter — no sign-up, no watermarks, results in under 3 seconds.

Try It Free — Convert Image to SVG