### CommonJS / Browserify Integration Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Demonstrates how to install and use svg-pan-zoom with CommonJS bundlers like Browserify or webpack. ```APIDOC ## CommonJS / Browserify Integration ### Description svg-pan-zoom is published to npm and works with CommonJS bundlers via `require`. ### Installation ```bash npm install svg-pan-zoom ``` ### Usage ```javascript var svgPanZoom = require('svg-pan-zoom'); // Use exactly as the standalone global document.addEventListener('DOMContentLoaded', function() { var instance = svgPanZoom('#my-svg', { panEnabled: true, zoomEnabled: true, controlIconsEnabled: true, minZoom: 0.1, maxZoom: 100 }); instance.zoom(1.5); instance.center(); }); ``` ``` -------------------------------- ### Custom Event Handling with Hammer.js Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Example demonstrating how to integrate custom event handling using Hammer.js, including disabling default listeners and defining init/destroy callbacks. ```APIDOC ## Custom Event Handling with Hammer.js ### Description This example shows how to use the `customEventsHandler` option to integrate external libraries like Hammer.js for advanced touch event handling. It includes disabling default listeners and defining custom `init` and `destroy` functions. ### Options - `haltEventListeners` (Array) - Specifies default event listeners to disable. - `init` (Function) - A function called when svg-pan-zoom is initialized. Receives an object with `svgElement` and `instance`. - `destroy` (Function) - A function called when svg-pan-zoom is destroyed. ``` -------------------------------- ### Use svg-pan-zoom with Browserify Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Install the package using npm and then require it in your source file. The library can then be used globally as usual. ```bash npm install --save bumbu/svg-pan-zoom ``` ```javascript svgPanZoom = require('svg-pan-zoom') // Use in the same way as you would do with global svgPanZoom: instance = svgPanZoom('#demo-tiger') ``` -------------------------------- ### CommonJS/Browserify Integration for SVG Pan Zoom Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Install via npm and use `require` to integrate svg-pan-zoom into your project. Initialization is similar to the standalone global usage. ```javascript // npm install svg-pan-zoom var svgPanZoom = require('svg-pan-zoom'); // Use exactly as the standalone global document.addEventListener('DOMContentLoaded', function() { var instance = svgPanZoom('#my-svg', { panEnabled: true, zoomEnabled: true, controlIconsEnabled: true, minZoom: 0.1, maxZoom: 100 }); instance.zoom(1.5); instance.center(); }); ``` -------------------------------- ### Initialize svg-pan-zoom with DOM Element Reference Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Initializes svg-pan-zoom using a direct reference to the SVG DOM element, offering an alternative to CSS selectors. This example also enables control icons. ```javascript var svgEl = document.getElementById('diagram'); var panZoom2 = svgPanZoom(svgEl, { controlIconsEnabled: true }); ``` -------------------------------- ### Getting SVG Sizes Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Retrieves detailed information about the SVG's current dimensions and zoom state. ```APIDOC ## Getting SVG Sizes ### Description Obtain detailed metrics about the SVG, including its cached dimensions and current zoom transformation. ### Methods - **getSizes()**: Returns an object containing SVG size information. - Returns: - `width` (Number) - The cached width of the SVG. - `height` (Number) - The cached height of the SVG. - `realZoom` (Number) - The current zoom scale derived from the transform matrix. - Example: `var sizes = panZoomTiger.getSizes(); console.log(sizes.width, sizes.height, sizes.realZoom);` ``` -------------------------------- ### Initialize svg-pan-zoom with All Options Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Full initialization of svg-pan-zoom with all available configuration options. This allows fine-grained control over panning, zooming, event handling, and more. ```javascript var panZoom = svgPanZoom('#diagram', { viewportSelector: '.svg-pan-zoom_viewport', // CSS selector or SVGElement for the viewport panEnabled: true, // Allow mouse/touch panning controlIconsEnabled: false, // Show built-in zoom +/- icons zoomEnabled: true, // Allow mouse/touch zooming dblClickZoomEnabled: true, // Double-click zooms in (shift+double-click zooms out) mouseWheelZoomEnabled: true, // Mouse wheel controls zoom preventMouseEventsDefault: true, // Call preventDefault on mouse/touch events zoomScaleSensitivity: 0.2, // Step size per wheel tick or zoomIn/zoomOut call minZoom: 0.5, // Minimum allowed zoom level (relative to initial) maxZoom: 10, // Maximum allowed zoom level (relative to initial) fit: true, // Scale viewport to fit SVG on init contain: false, // Scale viewport to contain SVG (fit takes precedence) center: true, // Center viewport in SVG on init refreshRate: 'auto', // Frame rate cap; 'auto' uses requestAnimationFrame beforeZoom: function(oldScale, newScale) { console.log('zooming from', oldScale, 'to', newScale); }, onZoom: function(newScale) { console.log('zoom level:', newScale); }, beforePan: function(oldPan, newPan) { return true; /* return false to cancel */ }, onPan: function(newPan) { console.log('pan:', newPan.x, newPan.y); }, onUpdatedCTM: function(ctm) { console.log('CTM updated', ctm); }, customEventsHandler: null, // Object with init/destroy/haltEventListeners eventsListenerElement: null // Attach events to a different element than the SVG }); ``` -------------------------------- ### Get SVG Size Information Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md The `getSizes` method returns an object containing the SVG's cached width, height, and current zoom level (`realZoom`). ```javascript var sizes = panZoomTiger.getSizes(); console.log(sizes.width, sizes.height, sizes.realZoom); ``` -------------------------------- ### Initialize Thumbnail Viewer Source: https://github.com/bumbu/svg-pan-zoom/blob/master/demo/thumbnailViewer.html Initializes the thumbnail viewer component with specified IDs for the main view and thumbnail view. ```javascript thumbnailViewer({mainViewId: 'mainView',thumbViewId: 'thumbView'}); ``` -------------------------------- ### SVG Pan Zoom Configuration Options Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Provides a list of configuration options that can be passed during initialization to customize the behavior of svg-pan-zoom. ```APIDOC ## SVG Pan Zoom Configuration Options ### Description Provides a list of configuration options that can be passed during initialization to customize the behavior of svg-pan-zoom. ### Method `svgPanZoom(selectorOrElement, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript svgPanZoom('#demo-tiger', { viewportSelector: '.svg-pan-zoom_viewport', panEnabled: true, controlIconsEnabled: false, zoomEnabled: true, dblClickZoomEnabled: true, mouseWheelZoomEnabled: true, preventMouseEventsDefault: true, zoomScaleSensitivity: 0.2, minZoom: 0.5, maxZoom: 10, fit: true, contain: false, center: true, refreshRate: 'auto', beforeZoom: function(){}, onZoom: function(){}, beforePan: function(){}, onPan: function(){}, onUpdatedCTM: function(){}, customEventsHandler: {}, eventsListenerElement: null }); ``` ### Response #### Success Response (200) N/A (Configuration options are passed during initialization) #### Response Example N/A ### Configuration Options Details: * **'viewportSelector'** (SVGElement | string): Can be a querySelector string or SVGElement. Default: null. * **'panEnabled'** (boolean): Enables or disables panning. Default: true. * **'controlIconsEnabled'** (boolean): Enables or disables control icons. Default: false. * **'zoomEnabled'** (boolean): Enables or disables zooming. Default: true. * **'dblClickZoomEnabled'** (boolean): Enables or disables double-click to zoom. Default: true. * **'mouseWheelZoomEnabled'** (boolean): Enables or disables mouse wheel zooming. Default: true. * **'preventMouseEventsDefault'** (boolean): Prevents default mouse event behavior. Default: true. * **'zoomScaleSensitivity'** (number): Sensitivity for zoom scaling. Default: 0.2. * **'minZoom'** (number): Minimum zoom level. Default: 0.5. * **'maxZoom'** (number): Maximum zoom level. Default: 10. * **'fit'** (boolean): Fits the SVG to the viewport. Default: true. * **'contain'** (boolean): Contains the SVG within the viewport. Default: false. * **'center'** (boolean): Centers the SVG in the viewport. Default: true. * **'refreshRate'** (number | string): Refresh rate for updates. Can be a number or 'auto'. Default: 'auto'. * **'beforeZoom'** (function): Callback function called before zoom changes. * **'onZoom'** (function): Callback function called when zoom changes. * **'beforePan'** (function): Callback function called before pan changes. * **'onPan'** (function): Callback function called when pan changes. * **'onUpdatedCTM'** (function): Callback function called when the CTM (Current Transformation Matrix) is updated. * **'customEventsHandler'** (object): Object with `init` and `destroy` functions for custom event handling. * **'eventsListenerElement'** (SVGElement | null): Element to listen for events on. Default: null. ``` -------------------------------- ### Initialize svg-pan-zoom with Default Options Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Minimal initialization of svg-pan-zoom using a CSS selector. All default options are applied. ```html ``` ```javascript var panZoom = svgPanZoom('#diagram'); ``` -------------------------------- ### Initialize Multiple SVG Pan Zoom Instances Source: https://github.com/bumbu/svg-pan-zoom/blob/master/demo/multi-instance.html Initializes multiple svg-pan-zoom instances for different SVG elements. Avoid using window.onload in production as it only supports a single listener. Ensure target SVGs exist before initialization. ```javascript // Don't use window.onLoad like this in production, because it can only listen to one function. window.onload = function() { // Expose variable for testing purposes window.panZoomTiger = svgPanZoom('#demo-tiger', { zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true }); // Expose variable for testing purposes window.panZoomPenguin = svgPanZoom('#demo-penguin', { zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true }); // Expose variable for testing purposes window.panZoomPenguin = svgPanZoom('#pvjs-diagram-2', { zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true }); // Expose variable for testing purposes window.panZoomPenguin = svgPanZoom('#pvjs-diagram-1', { zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true }); }; ``` -------------------------------- ### Custom Event Handler for SVG Pan Zoom Source: https://github.com/bumbu/svg-pan-zoom/blob/master/demo/custom-event-handlers.html Implement custom event handlers for SVG elements to manage zoom states and update CSS classes. This example uses a customEventsHandler object with init and destroy methods. ```javascript window.onload = function() { var svgActive = false, svgHovered = false; // Expose to window namespace for testing purposes window.panZoom = svgPanZoom('#limit-svg', { zoomEnabled: true, controlIconsEnabled: true, zoomEnabled: false, fit: 1, center: 1, customEventsHandler: { init: function(options) { function updateSvgClassName() { options.svgElement.setAttribute('class', '' + (svgActive ? 'active' : '') + (svgHovered ? ' hovered' : '')) } this.listeners = { click: function() { if (svgActive) { options.instance.disableZoom() svgActive = false } else { options.instance.enableZoom() svgActive = true } updateSvgClassName() }, mouseenter: function() { svgHovered = true updateSvgClassName() }, mouseleave: function() { svgActive = false svgHovered = false options.instance.disableZoom() updateSvgClassName() } } this.listeners.mousemove = this.listeners.mouseenter; for (var eventName in this.listeners) { options.svgElement.addEventListener(eventName, this.listeners[eventName]) } }, destroy: function(options) { for (var eventName in this.listeners) { options.svgElement.removeEventListener(eventName, this.listeners[eventName]) } } } }); }; ``` -------------------------------- ### Responsive Fit and Center on Resize Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Call `resize`, `fit`, and `center` in sequence to ensure the SVG content is correctly scaled and positioned after its container is resized. ```javascript // Get instance var panZoomTiger = svgPanZoom('#demo-tiger'); panZoomTiger.resize(); // update SVG cached size and controls positions panZoomTiger.fit(); panZoomTiger.center(); ``` -------------------------------- ### Get SVG Sizes and Transform State Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt The `getSizes()` method returns current dimensions and transform state, useful for calculating boundary limits or SVG coordinates. It provides SVG element dimensions, real zoom level, and viewBox properties. ```javascript var pz = svgPanZoom('#diagram', { fit: true, center: true }); var sizes = pz.getSizes(); /* sizes = { width: 700, // SVG element width in px height: 500, // SVG element height in px realZoom: 0.714, // Current absolute scale (a/d of SVGMatrix) viewBox: { x: 0, // viewBox x offset y: 0, // viewBox y offset width: 980, // Content width in SVG units height: 700 // Content height in SVG units } } */ // Example: compute the SVG coordinate at the center of the visible viewport var centerX = (-pz.getPan().x + sizes.width / 2) / sizes.realZoom; var centerY = (-pz.getPan().y + sizes.height / 2) / sizes.realZoom; console.log('Viewport center in SVG coords:', centerX, centerY); // Example: check if SVG content fits within container var fitZoomW = sizes.width / sizes.viewBox.width; var fitZoomH = sizes.height / sizes.viewBox.height; var isFit = Math.abs(sizes.realZoom - Math.min(fitZoomW, fitZoomH)) < 0.001; console.log('Is fitted:', isFit); ``` -------------------------------- ### Set Zoom Bounds and Sensitivity Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Configure minimum and maximum zoom levels, and adjust the sensitivity of zoom actions. Zoom bounds are relative to the initial fit state. Values outside the bounds are silently clamped. ```javascript var pz = svgPanZoom('#chart', { minZoom: 0.5, maxZoom: 10, zoomScaleSensitivity: 0.2 }); // Change bounds at runtime pz.setMinZoom(0.1); // allow zooming out further pz.setMaxZoom(50); // allow zooming in more pz.setZoomScaleSensitivity(0.5); // coarser steps // Verify clamping: attempting to set zoom beyond max is silently clamped pz.zoom(100); console.log(pz.getZoom()); // → 50 (the new max) pz.zoom(0.001); console.log(pz.getZoom()); // → 0.1 (the new min) // Fine-grained sensitivity for precision work pz.setZoomScaleSensitivity(0.05); var before = pz.getZoom(); pz.zoomIn(); console.log((pz.getZoom() - before).toFixed(4)); // small increment ~0.05× ``` -------------------------------- ### Resize Handling: resize() and updateBBox() Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt These methods are used to handle changes in the SVG container or its content. `resize()` should be called when the container element changes size, and `updateBBox()` should be called when the SVG's content changes. ```APIDOC ## resize() ### Description Must be called after the SVG's container element changes size so the library can recalculate cached dimensions and reposition on-screen control icons. ### Method `resize()` ### Example ```javascript window.addEventListener('resize', function() { pz.resize(); // update cached SVG dimensions + reposition icons pz.fit(); // re-scale to new container size pz.center(); // re-center }); ``` ## updateBBox() ### Description Must be called after the SVG's *content* changes (elements added, removed, or resized) so the library recalculates the viewport bounding box for `fit`, `contain`, and `center`. ### Method `updateBBox()` ### Example ```javascript document.getElementById('box').setAttribute('width', 800); pz.updateBBox(); // recalculate bounding box of #content pz.fit(); // now fit() uses the correct new bounding box pz.center(); ``` ``` -------------------------------- ### Initialization - svgPanZoom(elementOrSelector, options) Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Initializes svg-pan-zoom on an SVG element. It accepts either a CSS selector string or a DOM element reference for the SVG. The function returns a public API instance for controlling the pan and zoom behavior. Calling it again on the same element returns the existing instance. ```APIDOC ## Initialization — `svgPanZoom(elementOrSelector, options)` Initializes svg-pan-zoom on an SVG element identified by a CSS selector string or a DOM element reference, returning a public API instance. Calling `svgPanZoom` on the same element again returns the existing instance. Accepts an ``, ``, or `` element (but **not** ``). ### Parameters #### `elementOrSelector` - **Type**: `string` or `HTMLElement` - **Description**: A CSS selector string or a DOM element reference to the SVG element. #### `options` (optional) - **Type**: `object` - **Description**: An object containing configuration options for pan and zoom behavior. ##### Available Options: - **`viewportSelector`** (string or HTMLElement): CSS selector or SVGElement for the viewport ``. - **`panEnabled`** (boolean): Allow mouse/touch panning. Defaults to `true`. - **`controlIconsEnabled`** (boolean): Show built-in zoom +/- icons. Defaults to `false`. - **`zoomEnabled`** (boolean): Allow mouse/touch zooming. Defaults to `true`. - **`dblClickZoomEnabled`** (boolean): Double-click zooms in (shift+double-click zooms out). Defaults to `true`. - **`mouseWheelZoomEnabled`** (boolean): Mouse wheel controls zoom. Defaults to `true`. - **`preventMouseEventsDefault`** (boolean): Call preventDefault on mouse/touch events. Defaults to `true`. - **`zoomScaleSensitivity`** (number): Step size per wheel tick or zoomIn/zoomOut call. Defaults to `0.2`. - **`minZoom`** (number): Minimum allowed zoom level (relative to initial). Defaults to `0.5`. - **`maxZoom`** (number): Maximum allowed zoom level (relative to initial). Defaults to `10`. - **`fit`** (boolean): Scale viewport to fit SVG on init. Defaults to `true`. - **`contain`** (boolean): Scale viewport to contain SVG (fit takes precedence). Defaults to `false`. - **`center`** (boolean): Center viewport in SVG on init. Defaults to `true`. - **`refreshRate`** (string or number): Frame rate cap; 'auto' uses requestAnimationFrame. Defaults to `'auto'`. - **`beforeZoom`** (function): Callback function executed before zoom. Receives `(oldScale, newScale)`. - **`onZoom`** (function): Callback function executed after zoom. Receives `(newScale)`. - **`beforePan`** (function): Callback function executed before pan. Receives `(oldPan, newPan)`. Return `false` to cancel. - **`onPan`** (function): Callback function executed after pan. Receives `(newPan)`. - **`onUpdatedCTM`** (function): Callback function executed when the CTM is updated. Receives `(ctm)`. - **`customEventsHandler`** (object): Object with `init`, `destroy`, `haltEventListeners` methods for custom event handling. - **`eventsListenerElement`** (HTMLElement): Element to attach events to, instead of the SVG element. ### Request Example ```javascript // Minimal initialization var panZoom = svgPanZoom('#diagram'); // Full initialization with all available options var panZoom = svgPanZoom('#diagram', { viewportSelector: '.svg-pan-zoom_viewport', panEnabled: true, controlIconsEnabled: false, zoomEnabled: true, dblClickZoomEnabled: true, mouseWheelZoomEnabled: true, preventMouseEventsDefault: true, zoomScaleSensitivity: 0.2, minZoom: 0.5, maxZoom: 10, fit: true, contain: false, center: true, refreshRate: 'auto', beforeZoom: function(oldScale, newScale) { console.log('zooming from', oldScale, 'to', newScale); }, onZoom: function(newScale) { console.log('zoom level:', newScale); }, beforePan: function(oldPan, newPan) { return true; /* return false to cancel */ }, onPan: function(newPan) { console.log('pan:', newPan.x, newPan.y); }, onUpdatedCTM: function(ctm) { console.log('CTM updated', ctm); }, customEventsHandler: null, eventsListenerElement: null }); // Using a DOM element reference var svgEl = document.getElementById('diagram'); var panZoom2 = svgPanZoom(svgEl, { controlIconsEnabled: true }); ``` ``` -------------------------------- ### Initialize svg-pan-zoom with Options Source: https://github.com/bumbu/svg-pan-zoom/blob/master/demo/inline-viewbox-zoomed.html Initializes the svg-pan-zoom plugin on an SVG element with specific options for zoom, controls, fitting, and centering. Avoid using window.onload in production as it can only attach one function. ```javascript window.onload = function() { svgPanZoom('#demo-tiger', { zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true, minZoom: 0.1 }); }; ``` -------------------------------- ### Programmatic Pan Control Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Demonstrates how to programmatically pan the SVG content using the `pan` and `panBy` methods. ```APIDOC ## Programmatic Pan Control ### Description Control the SVG viewport's position programmatically. The `pan` method moves to a specific point, while `panBy` moves relative to the current position. ### Methods - **pan(vector)**: Pans the SVG to a specific point. - `vector` (Object) - An object with `x` and `y` properties representing the target coordinates. - Example: `panZoomTiger.pan({x: 50, y: 50})` - **panBy(vector)**: Pans the SVG by a relative amount. - `vector` (Object) - An object with `x` and `y` properties representing the offset. - Example: `panZoomTiger.panBy({x: 50, y: 50})` ``` -------------------------------- ### Initialize svg-pan-zoom with Options Source: https://github.com/bumbu/svg-pan-zoom/blob/master/demo/wikipathways.html Initializes svg-pan-zoom on an SVG element with zoom and control icons enabled. Avoid using window.onload in production as it can only listen to one function. ```javascript window.onload = function() { svgPanZoom('#pvjs-diagram-1', { zoomEnabled: true, controlIconsEnabled: true }); }; ``` -------------------------------- ### Initialize and Animate SVG Pan Zoom Source: https://github.com/bumbu/svg-pan-zoom/blob/master/demo/simple-animation.html Initializes svg-pan-zoom with specific options and sets up an animation function for custom panning. Avoid using window.onload in production. ```javascript window.onload = function() { // Expose to window namespase for testing purposes window.panZoomInstance = svgPanZoom('#svg-id', { zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true, minZoom: 0.1 }); // Zoom out panZoomInstance.zoom(0.2); function customPanBy(amount){ // {x: 1, y: 2} var animationTime = 300 // ms , animationStepTime = 15 // one frame per 30 ms , animationSteps = animationTime / animationStepTime , animationStep = 0 , intervalID = null , stepX = amount.x / animationSteps , stepY = amount.y / animationSteps intervalID = setInterval(function(){ if (animationStep++ < animationSteps) { panZoomInstance.panBy({x: stepX, y: stepY}) } else { // Cancel interval clearInterval(intervalID) } }, animationStepTime) } var button = document.getElementById("animate") button.addEventListener("click", function() { // Pan by any values from -80 to 80 customPanBy({x: Math.round(Math.random() * 160 - 80), y: Math.round(Math.random() * 160 - 80)}) }); }; ``` -------------------------------- ### Initialize SVG Pan Zoom Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Initialize the svg-pan-zoom library by referencing the script and calling the `svgPanZoom` function. The function accepts a CSS selector or a DOM element representing the SVG. ```javascript var panZoomTiger = svgPanZoom('#demo-tiger'); ``` ```javascript var svgElement = document.querySelector('#demo-tiger') var panZoomTiger = svgPanZoom(svgElement) ``` -------------------------------- ### Zoom Bounds & Sensitivity Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Configure the minimum and maximum zoom levels allowed, and adjust the sensitivity of zoom operations triggered by user input or API calls. ```APIDOC ## Zoom Bounds & Sensitivity — `setMinZoom`, `setMaxZoom`, `setZoomScaleSensitivity` ### Description Sets the boundaries for zoom levels and controls the step size for zoom actions, affecting both user interactions and programmatic zoom. ### Methods - `setMinZoom(zoomLevel)`: Sets the minimum allowed zoom level. Values are relative to the initial fit. - `setMaxZoom(zoomLevel)`: Sets the maximum allowed zoom level. Values are relative to the initial fit. - `setZoomScaleSensitivity(sensitivity)`: Sets the sensitivity for zoom operations. A lower value results in finer steps. ### Example ```javascript var pz = svgPanZoom('#chart', { minZoom: 0.5, maxZoom: 10, zoomScaleSensitivity: 0.2 }); // Change bounds at runtime pz.setMinZoom(0.1); pz.setMaxZoom(50); pz.setZoomScaleSensitivity(0.5); // Verify clamping pz.zoom(100); // Clamped to maxZoom pz.zoom(0.001); // Clamped to minZoom ``` ``` -------------------------------- ### Thumbnail Viewer CSS Styling Source: https://github.com/bumbu/svg-pan-zoom/blob/master/demo/thumbnailViewer.html Styles for the main view container, thumbnail view, and scope container. ```css html,body{ width: 100%; height: 100%; } #mainViewContainer { width: 95%; height: 95%; border: 1px solid black; margin: 10px; padding: 3px; overflow: hidden; } #mainView { width: 100%; height: 100%; min-height: 100%; display: inline; } .thumbViewClass { border: 1px solid black; position: absolute; bottom: 5px; left: 5px; width: 20%; height: 30%; margin: 3px; padding: 3px; overflow: hidden; } #thumbView { z-index: 110; background: white; } #scopeContainer { z-index: 120; } ``` -------------------------------- ### Implement Custom Pan Limits Source: https://github.com/bumbu/svg-pan-zoom/blob/master/demo/limit-pan.html Use the beforePan option to define custom panning boundaries. This function is called before each pan operation, allowing you to modify the new pan values to enforce limits. Note: Avoid using window.onload in production as it can only attach one function. ```javascript // Don't use window.onLoad like this in production, because it can only listen to one function. window.onload = function() { var beforePan beforePan = function(oldPan, newPan){ var stopHorizontal = false var stopVertical = false var gutterWidth = 100 var gutterHeight = 100 // Computed variables var sizes = this.getSizes() var leftLimit = -((sizes.viewBox.x + sizes.viewBox.width) * sizes.realZoom) + gutterWidth var rightLimit = sizes.width - gutterWidth - (sizes.viewBox.x * sizes.realZoom) var topLimit = -((sizes.viewBox.y + sizes.viewBox.height) * sizes.realZoom) + gutterHeight var bottomLimit = sizes.height - gutterHeight - (sizes.viewBox.y * sizes.realZoom) var customPan = {} customPan.x = Math.max(leftLimit, Math.min(rightLimit, newPan.x)) customPan.y = Math.max(topLimit, Math.min(bottomLimit, newPan.y)) return customPan } // Expose to window namespace for testing purposes window.panZoom = svgPanZoom('#limit-svg', { zoomEnabled: true, controlIconsEnabled: true, fit: 1, center: 1, beforePan: beforePan }); // panZoom.setBeforePan(beforePan) } ``` -------------------------------- ### SVG Pan & Zoom Callbacks Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Implement `beforePan`, `onPan`, `beforeZoom`, and `onZoom` callbacks to intercept and modify or react to pan and zoom events. Callbacks can be set at initialization or dynamically. ```javascript // Pan-limiting: keep at least 100px of SVG visible on each edge var beforePan = function(oldPan, newPan) { var gutterW = 100, gutterH = 100; var sizes = this.getSizes(); var leftLimit = -((sizes.viewBox.x + sizes.viewBox.width) * sizes.realZoom) + gutterW; var rightLimit = sizes.width - gutterW - (sizes.viewBox.x * sizes.realZoom); var topLimit = -((sizes.viewBox.y + sizes.viewBox.height) * sizes.realZoom) + gutterH; var bottomLimit = sizes.height - gutterH - (sizes.viewBox.y * sizes.realZoom); return { x: Math.max(leftLimit, Math.min(rightLimit, newPan.x)), y: Math.max(topLimit, Math.min(bottomLimit, newPan.y)) }; }; var pz = svgPanZoom('#bounded', { fit: true, center: true, beforePan: beforePan }); // Dynamically swap out the beforeZoom callback pz.setBeforeZoom(function(oldScale, newScale) { if (newScale > 5) { console.warn('Max zoom 5 enforced by beforeZoom'); return false; // cancel } }); // Log every completed zoom pz.setOnZoom(function(scale) { console.log('Zoomed to', scale.toFixed(3)); }); // Log every completed pan pz.setOnPan(function(point) { console.log('Panned to', JSON.stringify(point)); }); // Remove a callback pz.setBeforeZoom(null); pz.setOnPan(null); ``` -------------------------------- ### Zoom Scale Sensitivity and Limits Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Configure the zoom behavior by adjusting the scale sensitivity and setting minimum and maximum zoom levels. ```APIDOC ## Zoom Scale Sensitivity and Limits ### Description Customize the zoom experience by adjusting how sensitive the zoom is to user input and by defining the boundaries for zoom levels. ### Methods - **setZoomScaleSensitivity(scale)**: Sets the sensitivity for zoom scaling. - `scale` (Number) - The sensitivity factor. - Example: `panZoomTiger.setZoomScaleSensitivity(0.5)` - **setMinZoom(zoom)**: Sets the minimum allowed zoom level. - `zoom` (Number) - The minimum zoom scale. - Example: `panZoomTiger.setMinZoom(0.5)` - **setMaxZoom(zoom)**: Sets the maximum allowed zoom level. - `zoom` (Number) - The maximum zoom scale. - Example: `panZoomTiger.setMaxZoom(5)` ``` -------------------------------- ### Custom Events Handler Configuration Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Implement custom event handling by providing an object with 'haltEventListeners', 'init', and 'destroy' functions to the 'customEventsHandler' option. ```javascript customEventsHandler: { haltEventListeners: [], init: function() { // custom initialization }, destroy: function() { // custom cleanup } } ``` -------------------------------- ### Initialize svg-pan-zoom with Custom Event Handling Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Use this snippet to initialize svg-pan-zoom and integrate custom event handling, such as double-tap zoom using Hammer.js. The `haltEventListeners` option prevents default touch event conflicts. ```javascript var options = { zoomEnabled: true , controlIconsEnabled: true , customEventsHandler: { // Halt all touch events haltEventListeners: ['touchstart', 'touchend', 'touchmove', 'touchleave', 'touchcancel'] // Init custom events handler , init: function(options) { // Init Hammer this.hammer = Hammer(options.svgElement) // Handle double tap this.hammer.on('doubletap', function(ev){ options.instance.zoomIn() }) } // Destroy custom events handler , destroy: function(){ this.hammer.destroy() } } } svgPanZoom('#mobile-svg', options); ``` -------------------------------- ### Handle SVG Resizing: resize() and updateBBox() Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Call `resize()` after container size changes and `updateBBox()` after SVG content changes. `resize()` recalculates cached dimensions and repositions controls, while `updateBBox()` recalculates the viewport bounding box for fitting and centering operations. ```html
``` -------------------------------- ### Configure SVG Pan Zoom with Options Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Customize the pan and zoom behavior by providing an options object as the second argument to the `svgPanZoom` function. This allows for fine-tuning of various parameters like zoom sensitivity, zoom limits, and event handling. ```javascript svgPanZoom('#demo-tiger', { viewportSelector: '.svg-pan-zoom_viewport' , panEnabled: true , controlIconsEnabled: false , zoomEnabled: true , dblClickZoomEnabled: true , mouseWheelZoomEnabled: true , preventMouseEventsDefault: true , zoomScaleSensitivity: 0.2 , minZoom: 0.5 , maxZoom: 10 , fit: true , contain: false , center: true , refreshRate: 'auto' , beforeZoom: function(){} , onZoom: function(){} , beforePan: function(){} , onPan: function(){} , onUpdatedCTM: function(){} , customEventsHandler: {} , eventsListenerElement: null }); ``` -------------------------------- ### Zoom API Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt These methods programmatically control the zoom level. They allow setting an absolute zoom level, multiplying the current zoom by a factor, or stepping zoom in/out. All zoom methods return the public instance, enabling method chaining. Zoom values are always relative to the initial state. ```APIDOC ## Zoom API — `zoom`, `zoomBy`, `zoomIn`, `zoomOut`, `getZoom`, `resetZoom` ### Description These methods programmatically control the zoom level. `zoom(scale)` sets an absolute zoom level relative to the initial fit state; `zoomBy(scale)` multiplies the current zoom by the given factor; `zoomIn()` and `zoomOut()` step by `zoomScaleSensitivity`. All zoom methods return the public instance, enabling method chaining. Zoom values are always relative to the initial state (`1` = initial zoom after fit/contain/center are applied). ### Methods - `zoom(scale)`: Sets an absolute zoom level. - `zoomBy(scale)`: Multiplies the current zoom by the given factor. - `zoomIn()`: Increases zoom by `zoomScaleSensitivity`. - `zoomOut()`: Decreases zoom by `zoomScaleSensitivity`. - `getZoom()`: Returns the current zoom level. - `resetZoom()`: Resets the zoom to the initial state. ### Example Usage ```javascript // Set zoom to 2x the initial level pz.zoom(2); // Multiply current zoom by 1.5 pz.zoomBy(1.5); // Zoom in pz.zoomIn(); // Zoom out pz.zoomOut(); // Get current zoom level console.log(pz.getZoom()); // Reset zoom pz.resetZoom(); ``` ``` -------------------------------- ### Dynamically Load and Swap SVGs with svg-pan-zoom Source: https://github.com/bumbu/svg-pan-zoom/blob/master/demo/dynamic-load.html Initializes svg-pan-zoom on dynamically loaded SVGs. Use this to swap SVG content without full page reloads. Ensure the container element exists before appending new SVGs. ```javascript $(function() { var lastEventListener = null; function createNewEmbed(src) { var embed = document.createElement('embed'); embed.setAttribute('style', 'width: 500px; height: 500px; border:1px solid black;'); embed.setAttribute('type', 'image/svg+xml'); embed.setAttribute('src', src); document.getElementById('container').appendChild(embed) lastEventListener = function() { svgPanZoom(embed, { zoomEnabled: true, controlIconsEnabled: true }); } embed.addEventListener('load', lastEventListener) return embed } var lastEmbedSrc = 'tiger.svg', lastEmbed = createNewEmbed(lastEmbedSrc); function removeEmbed() { // Destroy svgpanzoom svgPanZoom(lastEmbed).destroy() // Remove event listener lastEmbed.removeEventListener('load', lastEventListener) // Null last event listener lastEventListener = null // Remove embed element document.getElementById('container').removeChild(lastEmbed) // Null reference to embed lastEmbed = null } $('#swap').on('click', function() { // Remove last added svg removeEmbed() if (lastEmbedSrc == 'tiger.svg') { lastEmbedSrc = 'Tux.svg' } else { lastEmbedSrc = 'tiger.svg' } lastEmbed = createNewEmbed(lastEmbedSrc) }) }); ``` -------------------------------- ### Initialize svg-pan-zoom for a Single SVG Layer Source: https://github.com/bumbu/svg-pan-zoom/blob/master/demo/layers.html Initializes svg-pan-zoom on a specific SVG element. Avoid using window.onload in production as it can only attach one function. Configure options like viewport selector, zoom, controls, fit, center, minZoom, and event listener element. ```javascript // Don't use window.onLoad like this in production, because it can only listen to one function. window.onload = function() { // Expose to window namespase for testing purposes window.panZoomInstance = svgPanZoom('#svg-1', { viewportSelector: '.svg-pan-zoom_viewport', zoomEnabled: true, controlIconsEnabled: true, fit: true, center: true, minZoom: 0.1, eventsListenerElement: document.querySelector('#svg-1 .svg-pan-zoom_viewport') }); }; ``` -------------------------------- ### Programmatic Pan Control Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Demonstrates how to programmatically pan the SVG content. Use `pan` for absolute positioning and `panBy` for relative movement. ```javascript // Get instance var panZoomTiger = svgPanZoom('#demo-tiger'); // Pan to rendered point x = 50, y = 50 panZoomTiger.pan({x: 50, y: 50}) // Pan by x = 50, y = 50 of rendered pixels panZoomTiger.panBy({x: 50, y: 50}) ``` -------------------------------- ### Initialize SVG Pan Zoom Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Initializes svg-pan-zoom on an SVG element. The first argument can be a CSS selector string or a DOM Element. ```APIDOC ## Initialize SVG Pan Zoom ### Description Initializes svg-pan-zoom on an SVG element. The first argument can be a CSS selector string or a DOM Element. ### Method `svgPanZoom(selectorOrElement, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript var panZoomTiger = svgPanZoom('#demo-tiger'); // or var svgElement = document.querySelector('#demo-tiger') var panZoomTiger = svgPanZoom(svgElement) ``` ### Response #### Success Response (200) Returns an instance of the svgPanZoom object. #### Response Example ```javascript // Returns an object with methods to control the SVG pan zoom instance { // methods like zoomIn, zoomOut, pan, etc. } ``` ``` -------------------------------- ### Zoom In, Zoom Out, and Reset Zoom Source: https://github.com/bumbu/svg-pan-zoom/blob/master/README.md Provides methods for simple zoom adjustments: `zoomIn`, `zoomOut`, and `resetZoom` to return to the initial scale. ```javascript // Get instance var panZoomTiger = svgPanZoom('#demo-tiger'); panZoomTiger.zoomIn() panZoomTiger.zoomOut() panZoomTiger.resetZoom() ``` -------------------------------- ### Implement Custom Event Handler with Hammer.js Source: https://context7.com/bumbu/svg-pan-zoom/llms.txt Replace default event listeners to integrate touch gesture libraries like Hammer.js for pinch-to-zoom and pan. Ensure the handler object has `haltEventListeners`, `init`, and `destroy` methods. ```html ```