Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing zoom in D3.js from mousewheel to control+mousewheel

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.

like image 733
Pedro Tabacof Avatar asked Jan 14 '16 20:01

Pedro Tabacof


2 Answers

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;
});
like image 110
Rico Sonntag Avatar answered Oct 23 '22 20:10

Rico Sonntag


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/

like image 28
Pedro Tabacof Avatar answered Oct 23 '22 21:10

Pedro Tabacof