What is d3-zoom?
The d3-zoom package is a JavaScript library that allows for interactive zooming and panning of elements in a document, typically used with SVG graphics. It is part of the D3 (Data-Driven Documents) collection of tools for manipulating documents based on data. d3-zoom enables users to apply zoom and pan transformations to visualizations, enhancing the interactivity and accessibility of data representations.
What are d3-zoom's main functionalities?
Zoom and Pan
This feature allows users to add zoom and pan interactions to an SVG element. The 'zoom' event listener applies the transformation to the SVG, updating its position and scale according to user interactions like mousewheel scrolling and dragging.
{"svg.call(d3.zoom().on('zoom', (event) => { svg.attr('transform', event.transform); }))"}
Control Zoom Scale
This feature lets users define the scale extent for the zoom, limiting how much the user can zoom in or out. In this example, the zoom scale is limited between 1x and 8x.
{"svg.call(d3.zoom().scaleExtent([1, 8]).on('zoom', (event) => { svg.attr('transform', event.transform); }))"}
Translate Extent
This feature restricts the panning to a specified rectangular area. In the code sample, the translate extent is set to the dimensions of the SVG, preventing panning outside of the SVG's viewbox.
{"svg.call(d3.zoom().translateExtent([[0, 0], [width, height]]).on('zoom', (event) => { svg.attr('transform', event.transform); }))"}
Programmatic Zooming
This feature allows for programmatic control of the zoom level, enabling transitions to a specific zoom level or transform. In this example, the SVG is programmatically zoomed to 2x scale over a 750ms transition.
{"svg.transition().duration(750).call(zoom.transform, d3.zoomIdentity.scale(2))"}
Other packages similar to d3-zoom
panzoom
Panzoom is a library for panning and zooming elements using CSS transforms. It is similar to d3-zoom but works with both SVG and HTML elements. Unlike d3-zoom, which is tightly integrated with D3's data-driven approach, panzoom is a more general-purpose library that can be used independently of any data visualization library.
leaflet
Leaflet is a JavaScript library for interactive maps. It includes functionalities for zooming and panning over map tiles. While d3-zoom is more generic and can be applied to any SVG element, Leaflet is specifically designed for map interactions and provides a wide range of map-specific features such as markers, layers, and controls.
d3-zoom
…
Installing
If you use NPM, npm install d3-zoom
. Otherwise, download the latest release. You can also load directly from d3js.org, either as a standalone library or as part of D3 4.0 alpha. AMD, CommonJS, and vanilla environments are supported. In vanilla, a d3_zoom
global is exported:
<script src="https://d3js.org/d3-zoom.v0.0.min.js"></script>
<script>
var zoom = d3_zoom.zoom();
</script>
Try d3-zoom in your browser.
API Reference
# d3.zoom()
…