Changing zoom in D3.js from mousewheel to control+

2019-07-09 05:10发布

问题:

From this question I know how to disable mousewheel zoom in D3.js. How can I remap it to holding control button down plus mousewheel? Thanks.

回答1:

I found a solution that does not need to modify the D3.js source.

I based my solution on this question: How to temporarily disable the zooming in d3.js

Instead of clicking on a button to enable/disable zooming, I used keydown/keyup events:

svg.call(zoom = d3.behavior.zoom().on('zoom', redrawOnZoom)).on('dblclick.zoom', null);

var zooming = false;

function redrawOnZoom() {
  if (zooming) {
    svgContainer.attr('transform', 'translate(' + zoom.translate() + ')' + ' scale(' + zoom.scale() + ')');
  }
};

d3.select("body").on("keydown", function () {
    zooming = d3.event.ctrlKey;
});

d3.select("body").on("keyup", function () {
     zooming = false;
});

Here is a complete fiddle: https://jsfiddle.net/tabacof/dcbor8eL/3/



回答2:

Add a filter function to the zoom handler (https://github.com/d3/d3-zoom#zoom_filter).

In d3.event the element ctrlKey (https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/ctrlKey) indicates if the control key was pressed or not.

Returning false in the filter function ignores the event.

zoom.filter(function () {
    return d3.event.ctrlKey;
});