Code

D3.js

Zoom & Pan

Advanced Attach d3.zoom() to an SVG to get scroll-to-zoom and drag-to-pan. Axes rescale in sync using transform.rescaleX/Y(). d3-zoom

const xBase = d3.scaleLinear()
  .domain([0, 100]).range([0, iW]);
const yBase = d3.scaleLinear()
  .domain([0, 100]).range([iH, 0]);

// Working copies updated by zoom
let x = xBase.copy();
let y = yBase.copy();

const zoom = d3.zoom()
  .scaleExtent([0.5, 20])
  .on('zoom', (event) => {
    // Derive new scales from transform
    x = event.transform.rescaleX(xBase);
    y = event.transform.rescaleY(yBase);

    // Redraw axes
    gXAxis.call(d3.axisBottom(x));
    gYAxis.call(d3.axisLeft(y));

    // Reposition points
    circles
      .attr('cx', d => x(d.x))
      .attr('cy', d => y(d.y));
  });

svg.call(zoom);   // attach to SVG element
Key APIs
  • d3.zoom() — zoom/pan behaviour factory
  • .scaleExtent([min, max]) — min/max zoom level
  • .translateExtent([[x0,y0],[x1,y1]]) — restrict panning area
  • event.transform.rescaleX(baseScale) — returns a new scale with the zoom transform applied
  • svg.call(zoom) — attaches wheel and pointer event listeners
  • Use a <clipPath> to prevent points from rendering outside the chart area