Add Smooth Zoom/Pan Interactions To SVGs With svg-pan-zoom Library

Category: Javascript , Zoom | February 29, 2024
Views Total:106 views
Official Page:Go to website
Last Update:February 29, 2024


Add Smooth Zoom/Pan Interactions To SVGs With svg-pan-zoom Library


svg-pan-zoom is a simple JavaScript library that adds interactive zooming and panning to your SVGs, whether they’re embedded using object element or displayed inline.

It can be useful for interactive maps, technical diagrams, or any detailed SVG graphics that require closer inspection.

More Like This:

How to use it:

1. Download and load the svg-pan-zoom.js script from dist folder.

<script src="/dist/svg-pan-zoom.min.js"></script>

2. Initialize the svgPanZoom on your SVG element.

<svg id="demo">
<!-- OR -->
<embed id="demo" type="image/svg+xml" style="width: 500px; height: 500px; border:1px solid black; " src="demo.svg" />
<!-- OR -->
<object id="demo" type="image/svg+xml" data="demo.svg" style="width: 500px; height: 500px; border:1px solid black; ">Your browser does not support SVG</object>
svgPanZoom('#demo', {
  // options

3. Available options to customize the zooming and panning behavior.

svgPanZoom('#demo', {
  // Viewport selector. Can be querySelector string or SVGElement
  viewportSelector: ".svg-pan-zoom_viewport",
  // enable or disable panning
  panEnabled: true, 
  // insert icons to give user an option in addition to mouse events to control pan/zoom
  controlIconsEnabled: false, 
  // enable or disable zooming
  zoomEnabled: true, 
  // enable or disable zooming by double clicking
  dblClickZoomEnabled: true, 
  // enable or disable zooming by mouse wheel
  mouseWheelZoomEnabled: true, 
  // enable or disable preventDefault for mouse events
  preventMouseEventsDefault: true, 
  // Zoom sensitivity
  zoomScaleSensitivity: 0.1, 
  // Minimum Zoom level
  minZoom: 0.5, 
  // Maximum Zoom level
  maxZoom: 10, 
  // enable or disable viewport fit in SVG
  fit: true, 
  // enable or disable viewport contain the svg
  contain: false, 
  // enable or disable viewport centering in SVG
  center: true, 
  // Maximum number of frames per second
  refreshRate: "auto", 
  // custom event handler
  customEventsHandler: null,
  eventsListenerElement: null,

4. Callback functions.

svgPanZoom('#demo', {
  beforeZoom: function(oldScale, newScale){},
  onZoom: function(scale){},
  beforePan: function(oldPoint, newPoint){},
  onPan: function(point){},
  onUpdatedCTM: function(ctm){},

You Might Be Interested In:

Leave a Reply