简体   繁体   中英

D3 combining selection with zoom/pan

I want to implement tree node selection alongside with zoom/pan. Considering that zoom/pan would conflict with selecting nodes with mouse (drag) I implemented as two separate listeners between which I can switch using CTRL keyboard button. Like this:

function toggleSelectZoom() {
    if (useZoom) {
        useZoom = false;
        zoomListener.on("zoom", null);
        container.classed("select", true)
            .on("mousedown.select", startNodeSelection)
            .on("mousemove.select", nodeSelection)
            .on("mouseup.select", endNodeSelection);
    } else {
        useZoom = true;
        container.classed("select", false)
            .on("mousedown.select", null)
            .on("mousemove.select", null)
            .on("mouseup.select", null);
        zoomListener.on("zoom", zoom);
    }
}

document.onkeydown = function(e) { if (e.ctrlKey) { toggleSelectZoom(); }};

But there is a problem: when switching to zoom/pan mode after drawing a selection frame in selection mode, the tree (when starting to pan) jumps to a position where it would be after the same manipulations in zoom/pan mode. Here is a fiddle http://jsfiddle.net/PSVW6/2/

The problem is that the zoom behaviour will still update its internal state, even if you're not acting on it. To solve, you have basically two options.

  • Reset the internal state of the zoom behaviour if not handling the event this way. This would require you to keep track of the zoom/translate state yourself.
  • Attach the zoom behaviour not to the entire SVG, but only to the elements themselves. This way, you would only be able to zoom/pan when the cursor is over an element and select elsewhere. This would eliminate the need for your switching logic in the handler, as the two sets of events would be separate.

It depends on your particular application which one of these solutions is more suitable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM