Convert Figma logo to code with AI

anvaka logopanzoom

Universal pan and zoom library (DOM, SVG, Custom)

1,779
285
1,779
164

Top Related Projects

JavaScript library that enables panning and zooming of an SVG in an HTML document, with mouse events or custom JavaScript hooks

An open-source, web-based viewer for zoomable images, implemented in pure JavaScript.

2,119

A library for panning and zooming elements using CSS transforms :mag:

Graph theory (network) library for visualisation and analysis

Quick Overview

Panzoom is a lightweight JavaScript library for adding pan and zoom functionality to HTML elements. It provides smooth, hardware-accelerated transformations and supports both mouse and touch interactions, making it ideal for creating interactive, zoomable interfaces in web applications.

Pros

  • Lightweight and performant, with minimal dependencies
  • Supports both mouse and touch interactions
  • Provides smooth, hardware-accelerated transformations
  • Highly customizable with various options and API methods

Cons

  • Limited built-in UI controls (e.g., zoom buttons)
  • May require additional setup for complex use cases
  • Documentation could be more comprehensive
  • Lacks advanced features like minimap or multi-touch gestures

Code Examples

  1. Basic initialization:
const element = document.getElementById('my-element');
const panzoom = Panzoom(element);
  1. Setting initial zoom and pan:
const panzoom = Panzoom(element, {
  startScale: 1.5,
  startX: 100,
  startY: 50
});
  1. Listening to events:
panzoom.on('panstart', (e) => {
  console.log('Pan started:', e);
});

panzoom.on('zoom', (e) => {
  console.log('Zoom level:', e.getTransform().scale);
});

Getting Started

  1. Install the library:
npm install panzoom
  1. Import and use in your project:
import Panzoom from '@panzoom/panzoom';

const element = document.getElementById('my-element');
const panzoom = Panzoom(element, {
  maxScale: 5,
  minScale: 0.5
});

// Add zoom in/out buttons
document.getElementById('zoom-in').addEventListener('click', panzoom.zoomIn);
document.getElementById('zoom-out').addEventListener('click', panzoom.zoomOut);

// Reset to initial state
document.getElementById('reset').addEventListener('click', panzoom.reset);

This setup creates a basic panzoom instance with zoom in, zoom out, and reset buttons. Adjust the options and add event listeners as needed for your specific use case.

Competitor Comparisons

JavaScript library that enables panning and zooming of an SVG in an HTML document, with mouse events or custom JavaScript hooks

Pros of svg-pan-zoom

  • Specifically designed for SVG elements, offering better performance and compatibility for SVG-based projects
  • Provides more SVG-specific features like viewport control and zoom limits
  • Has a larger community and more frequent updates

Cons of svg-pan-zoom

  • Limited to SVG elements, not suitable for general DOM manipulation
  • Slightly larger file size compared to panzoom
  • May have a steeper learning curve for developers unfamiliar with SVG manipulation

Code Comparison

svg-pan-zoom:

var panZoomInstance = svgPanZoom('#svg-id', {
  zoomEnabled: true,
  controlIconsEnabled: true,
  fit: true,
  center: true
});

panzoom:

const element = document.querySelector('#scene')
const panzoom = Panzoom(element, {
  maxScale: 5,
  minScale: 0.5
})

Both libraries offer similar core functionality for panning and zooming, but svg-pan-zoom is more tailored for SVG elements, while panzoom is more versatile and can be used with any DOM element. The choice between the two depends on the specific project requirements and whether SVG-specific features are needed.

An open-source, web-based viewer for zoomable images, implemented in pure JavaScript.

Pros of OpenSeadragon

  • More feature-rich, specifically designed for deep-zoom imaging
  • Supports multiple image formats and tiling systems
  • Extensive documentation and active community support

Cons of OpenSeadragon

  • Larger file size and potentially more complex setup
  • May be overkill for simple panning and zooming needs
  • Steeper learning curve for basic implementations

Code Comparison

OpenSeadragon:

var viewer = OpenSeadragon({
    id: "openseadragon1",
    prefixUrl: "/openseadragon/images/",
    tileSources: "/path/to/image.dzi"
});

Panzoom:

const element = document.querySelector('#scene')
const instance = panzoom(element, {
    maxZoom: 5,
    minZoom: 0.1
});

Key Differences

  • OpenSeadragon is specialized for deep-zoom imaging, while Panzoom is a more general-purpose pan and zoom library
  • Panzoom is lighter and easier to implement for basic use cases
  • OpenSeadragon offers more advanced features for complex image viewing scenarios

Use Case Recommendations

  • Choose OpenSeadragon for projects requiring advanced image viewing capabilities, especially with large, high-resolution images
  • Opt for Panzoom when you need a simple, lightweight solution for basic pan and zoom functionality on any DOM element
2,119

A library for panning and zooming elements using CSS transforms :mag:

Pros of panzoom (timmywil)

  • More extensive documentation and examples
  • Supports touch events and mobile devices out of the box
  • Offers more configuration options and customization

Cons of panzoom (timmywil)

  • Larger file size and potentially higher overhead
  • Less performant for large datasets or complex visualizations

Code Comparison

panzoom (anvaka):

const element = document.querySelector('#scene')
const instance = panzoom(element, {
  maxZoom: 5,
  minZoom: 0.1
})

panzoom (timmywil):

const element = document.getElementById('scene')
const panzoom = Panzoom(element, {
  maxScale: 5,
  minScale: 0.1
})

Both libraries provide similar basic functionality for panning and zooming elements. The anvaka version is more lightweight and focused on performance, making it suitable for large-scale visualizations or applications with limited resources. On the other hand, the timmywil version offers more features and better support for touch devices, making it a good choice for projects that require extensive customization and mobile compatibility.

The code comparison shows that both libraries have similar syntax for initialization, with slight differences in naming conventions for options. The timmywil version uses scale instead of zoom in its options, reflecting its broader feature set.

Graph theory (network) library for visualisation and analysis

Pros of Cytoscape.js

  • Comprehensive graph theory library with advanced features for complex network visualization and analysis
  • Extensive documentation and active community support
  • Built-in layout algorithms and styling options for graph elements

Cons of Cytoscape.js

  • Steeper learning curve due to its extensive feature set
  • Larger file size and potentially higher performance overhead for simple panning and zooming tasks
  • May be overkill for projects that only require basic pan and zoom functionality

Code Comparison

Panzoom:

const element = document.getElementById('scene')
const instance = panzoom(element, {
  maxZoom: 5,
  minZoom: 0.1
})

Cytoscape.js:

const cy = cytoscape({
  container: document.getElementById('cy'),
  elements: [ /* graph elements */ ],
  style: [ /* styling */ ],
  layout: { name: 'grid' }
})

Summary

Panzoom is a lightweight library focused specifically on panning and zooming functionality, making it ideal for simpler projects. Cytoscape.js, on the other hand, is a full-featured graph theory library that includes panning and zooming capabilities along with many other advanced features for complex network visualization and analysis. The choice between the two depends on the specific requirements of your project and the level of graph manipulation needed.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

panzoom build status

Extensible, mobile friendly pan and zoom framework (supports DOM and SVG).

Demo

Usage

Grab it from npm and use with your favorite bundler:

npm install panzoom --save

Or download from CDN:

<script src='https://unpkg.com/panzoom@9.4.0/dist/panzoom.min.js'></script>

If you download from CDN the library will be available under panzoom global name.

Pan and zoom DOM subtree

// just grab a DOM element
var element = document.querySelector('#scene')

// And pass it to panzoom
panzoom(element)

SVG panzoom example

<!-- this is your html file with svg -->
<body>
  <svg>
    <!-- this is the draggable root -->
    <g id='scene'> 
      <circle cx='10' cy='10' r='5' fill='pink'></circle>
    </g>
  </svg>
</body>
// In the browser panzoom is already on the
// window. If you are in common.js world, then 
// var panzoom = require('panzoom')

// grab the DOM SVG element that you want to be draggable/zoomable:
var element = document.getElementById('scene')

// and forward it it to panzoom.
panzoom(element)

If require a dynamic behavior (e.g. you want to make an element not draggable anymore, or even completely delete an SVG element) make sure to call dispose() method:

var instance = panzoom(element)
// do work
// ...
// then at some point you decide you don't need this anymore:
instance.dispose()

This will make sure that all event handlers are cleared and you are not leaking memory

Events notification

The library allows to subscribe to transformation changing events. E.g. when user starts/ends dragging the element, the element will fire panstart/panend events. Here is example of all supported events:

var instance = panzoom(element);
instance.on('panstart', function(e) {
  console.log('Fired when pan is just started ', e);
  // Note: e === instance.
});

instance.on('pan', function(e) {
  console.log('Fired when the `element` is being panned', e);
});

instance.on('panend', function(e) {
  console.log('Fired when pan ended', e);
});

instance.on('zoom', function(e) {
  console.log('Fired when `element` is zoomed', e);
});

instance.on('zoomend', function(e) {
  console.log('Fired when zoom animation ended', e);
});

instance.on('transform', function(e) {
  // This event will be called along with events above.
  console.log('Fired when any transformation has happened', e);
});

See JSFiddle console for a demo.

Ignore mouse wheel

Sometimes zooming interferes with scrolling. If you want to alleviate it you can provide a custom filter, which will allow zooming only when modifier key is down. E.g.

panzoom(element, {
  beforeWheel: function(e) {
    // allow wheel-zoom only if altKey is down. Otherwise - ignore
    var shouldIgnore = !e.altKey;
    return shouldIgnore;
  }
});

See JSFiddle for the demo. The tiger will be zoomable only when Alt key is down.

Ignore mouse down

If you want to disable panning or filter it by pressing a specific key, use the beforeMouseDown() option. E.g.

panzoom(element, {
  beforeMouseDown: function(e) {
    // allow mouse-down panning only if altKey is down. Otherwise - ignore
    var shouldIgnore = !e.altKey;
    return shouldIgnore;
  }
});

Note that it only works when the mouse initiates the panning and would not work for touch initiated events.

Ignore keyboard events

By default, panzoom will listen to keyboard events, so that users can navigate the scene with arrow keys and +, - signs to zoom out. If you don't want this behavior you can pass the filterKey() predicate that returns truthy value to prevent panzoom's default behavior:

panzoom(element, {
  filterKey: function(/* e, dx, dy, dz */) {
    // don't let panzoom handle this event:
    return true;
  }
});

Zoom Speed

You can adjust how fast it zooms, by passing optional zoomSpeed argument:

panzoom(element, {
  zoomSpeed: 0.065 // 6.5% per mouse wheel event
});

Pinch Speed

On touch devices zoom is achieved by "pinching" and depends on distance between two fingers. We try to match the zoom speed with pinch, but if you find that too slow (or fast), you can adjust it:

panzoom(element, {
  pinchSpeed: 2 // zoom two times faster than the distance between fingers
});

Get current transform (scale, offset)

To get the current zoom (scale) level use the getTransform() method:

console.log(instance.getTransform()); // prints {scale: 1.2, x: 10, y: 10}

Fixed transform origin when zooming

By default when you use mouse wheel or pinch to zoom, panzoom uses mouse coordinates to determine the central point of the zooming operation.

If you want to override this behavior and always zoom into center of the screen pass transformOrigin to the options:

panzoom(element, {
  // now all zoom operations will happen based on the center of the screen
  transformOrigin: {x: 0.5, y: 0.5}
});

You specify transformOrigin as a pair of {x, y} coordinates. Here are some examples:

// some of the possible values:
let topLeft = {x: 0, y: 0};
let topRight = {x: 1, y: 0};
let bottomLeft = {x: 0, y: 1};
let bottomRight = {x: 1, y: 1};
let centerCenter = {x: 0.5, y: 0.5};

// now let's use it:
panzoom(element, {
  transformOrigin: centerCenter
});

To get or set new transform origin use the following API:

let instance = panzoom(element, {
  // now all zoom operations will happen based on the center of the screen
  transformOrigin: {x: 0.5, y: 0.5}
});

let origin = instance.getTransformOrigin(); // {x: 0.5, y: 0.5}

instance.setTransformOrigin({x: 0, y: 0}); // now it is topLeft
instance.setTransformOrigin(null); // remove transform origin

Min Max Zoom

You can set min and max zoom, by passing optional minZoom and maxZoom argument:

var instance = panzoom(element, {
  maxZoom: 1,
  minZoom: 0.1
});

You can later get the values using getMinZoom() and getMaxZoom()

assert(instance.getMaxZoom() === 1);
assert(instance.getMinZoom() === 0.1);

Disable Smooth Scroll

You can disable smooth scroll, by passing optional smoothScroll argument:

panzoom(element, {
  smoothScroll: false
});

With this setting the momentum is disabled.

Pause/resume the panzoom

You can pause and resume the panzoom by calling the following methods:

var element = document.getElementById('scene');
var instance = panzoom(element);

instance.isPaused(); //  returns false
instance.pause();    //  Pauses event handling
instance.isPaused(); //  returns true now
instance.resume();   //  Resume panzoom
instance.isPaused(); //  returns false again

Script attachment

If you want to quickly play with panzoom without using javascript, you can configure it via script tag:

<!-- this is your html file -->
<!DOCTYPE html>
<html>
<head>
  <script src='https://unpkg.com/panzoom@9.4.0/dist/panzoom.min.js'
    query='#scene' name='pz'></script>
</head>
<body>
  <svg>
    <!-- this is the draggable root -->
    <g id='scene'> 
      <circle cx='10' cy='10' r='5' fill='pink'></circle>
    </g>
  </svg>
</body>
</html>

Most importantly, you can see query attribute that points to CSS selector. Once the element is found panzoom is attached to this element. The controller will become available under window.pz name. And you can pass additional options to the panzoom via attributes prefixed with pz-.

Here is a demo: Script based attributes

Adjust Double Click Zoom

You can adjust the double click zoom multiplier, by passing optional zoomDoubleClickSpeed argument.

When double clicking, zoom is multiplied by zoomDoubleClickSpeed, which means that a value of 1 will disable double click zoom completely.

panzoom(element, {
  zoomDoubleClickSpeed: 1, 
});

Set Initial Position And Zoom

You can set the initial position and zoom, by chaining the zoomAbs function with x position, y position and zoom as arguments:

panzoom(element, {
  maxZoom: 1,
  minZoom: 0.1,
  initialX: 300,
  initialY: 500,
  initialZoom: 0.5
});

Handling touch events

The library will handle ontouch events very aggressively, it will preventDefault, and stopPropagation for the touch events inside container. Sometimes this is not a desirable behavior.

If you want to take care about this yourself, you can pass onTouch callback to the options object:

panzoom(element, {
  onTouch: function(e) {
    // `e` - is current touch event.

    return false; // tells the library to not preventDefault.
  }
});

Note: if you don't preventDefault yourself - make sure you test the page behavior on iOS devices. Sometimes this may cause page to bounce undesirably.

Handling double click events

By default panzoom will prevent default action on double click events - this is done to avoid accidental text selection (which is default browser action on double click). If you prefer to allow default action, you can pass onDoubleClick() callback to options. If this callback returns false, then the library will not prevent default action:

panzoom(element, {
  onDoubleClick: function(e) {
    // `e` - is current double click event.

    return false; // tells the library to not preventDefault, and not stop propagation
  }
});

Bounds on Panzoom

By default panzoom will not prevent Image from Panning out of the Container. bounds (boolean) and boundsPadding (number) can be defined so that it doesn't fall out. Default value for boundsPadding is 0.05 .

panzoom(element, {
  bounds: true,
  boundsPadding: 0.1
});

Triggering Pan

To Pan the object using Javascript use moveTo(<number>,<number>) function. It expects x, y value to where to move.

instance.moveTo(0, 0);

To pan in a smooth way use smoothMoveTo(<number>,<number>):

instance.smoothMoveTo(0, 0);

Triggering Zoom

To Zoom the object using Javascript use zoomTo(<number>,<number>,<number>) function. It expects x, y value as coordinates of where to zoom. It also expects the zoom factor as the third argument. If zoom factor is greater than 1, apply zoom IN. If zoom factor is less than 1, apply zoom OUT.

instance.zoomTo(0, 0, 2);

To zoom in a smooth way use smoothZoom(<number>,<number>,<number>):

instance.smoothZoom(0, 0, 0.5);

Custom UI to trigger zoom

One of the common use case is to have a custom UI to trigger zoom. For example, you can use a button to zoom in/out. Since this library does not depend on any popular framework (react, vue, etc.) you can implement it yourself following this example:

license

MIT

NPM DownloadsLast 30 Days