DOM and SVG Pan and Zoom

9.4.4 · active · verified Tue Apr 21

panzoom is a standalone, extensible JavaScript library designed to add intuitive pan and zoom functionalities to both regular DOM elements and SVG graphics. Currently stable at version 9.4.4, the project is actively maintained, with incremental updates focusing on stability and feature enhancements. It offers a highly configurable API, allowing developers to customize interaction behaviors, such as filtering mouse wheel or mouse down events to prevent conflicts with page scrolling or other interactions. A key differentiator is its framework-agnostic design, directly manipulating the target element without imposing dependencies on specific UI frameworks, making it exceptionally versatile for embedding into any web application. It provides a comprehensive event system for tracking pan, zoom, and general transform changes, and importantly, includes a `dispose()` method to ensure proper cleanup of event listeners and prevent memory leaks, which is crucial for dynamic applications. The library ships with TypeScript types, enhancing developer experience in type-safe environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to apply pan and zoom functionality to a simple HTML element, including basic configuration options and event filtering for mouse wheel.

<html>
<head>
  <title>Panzoom Demo</title>
  <style>
    #container {
      width: 400px;
      height: 300px;
      border: 1px solid #ccc;
      overflow: hidden;
      position: relative;
    }
    #scene {
      width: 200px;
      height: 150px;
      background: lightblue;
      position: absolute;
      top: 50px;
      left: 50px;
      transform-origin: 0 0;
    }
  </style>
</head>
<body>
  <div id="container">
    <div id="scene">Drag and Zoom Me</div>
  </div>
  <script type="module">
    import panzoom from 'panzoom';

    const container = document.getElementById('container');
    const scene = document.getElementById('scene');

    const pz = panzoom(scene, {
      bounds: true,
      boundsPadding: 0.1,
      maxZoom: 4,
      minZoom: 0.5,
      // Example of custom filter: only zoom with Alt key pressed
      beforeWheel: function(e) {
        return !e.altKey;
      }
    });

    console.log('Panzoom initialized:', pz);

    // Optional: Dispose after some time or on element removal
    // setTimeout(() => {
    //   pz.dispose();
    //   console.log('Panzoom disposed.');
    // }, 10000);
  </script>
</body>
</html>

view raw JSON →