3

Out of the box, D3 V4 pan and zoom work perfectly for me using the following code:

const zoom = d3.zoom();
zoom.on("zoom", () => this.zoom());
this._svg.call(zoom);

zoom()
{
    this._svg_g.attr("transform", d3.event.transform);
}

Where _svg is an svg element and _svg_g is a top level g element within the svg.

However, what I would like to do is to associate the behavior with gestures that are different from the defaults.

I would like the behavior as follows:

Zoom

  • As currently with the mouse wheel, but only when Ctrl key is pressed.
  • On particular key presses (e.g. Ctrl+= or Ctrl+-).

Pan

  • As currently but only when Alt key is pressed.
  • Vertically with the mouse wheel and no modifier keys.
  • Horizontally with the mouse wheel when Shift is pressed.

The exact gestures are subject to change, but the essential elements are:

  • Enable zooming and panning only under certain conditions (e.g. modifier key pressed)
  • Trigger zooming and panning on events of my choosing
fractor
  • 1,534
  • 2
  • 15
  • 30

1 Answers1

4

You could use the filter function:

d3.zoom()
    .filter(() => {
      if (d3.event.type === 'wheel') {
        // don't allow zooming without pressing [ctrl] key
        return d3.event.ctrlKey;
      }

      return true;
    })
    .on('zoom', function () {
       this.zoomed();
    });
Tarzzzannn
  • 61
  • 3
  • How could I do this with the command key for apple computers? – Merc May 02 '23 at 15:27
  • Command key is `metaKey`: https://stackoverflow.com/a/3922353/1121268 Which is available in the d3 event object – Merc May 02 '23 at 15:35