在D3.js中,有没有任何方法可以将x和y方向上的滚动事件绑定到平移svg

in D3.js is there any way bind the scroll event in both the x and y directions to panning the svg?

本文关键字:滚动 方向 事件 绑定 svg js D3 有没有 任何 方法      更新时间:2023-09-26

当前,每当我向上或向下滚动时,我的d3树都有缩放行为。我想用平移来代替这种行为。有人知道我会怎么做吗?

    // Define the zoom function for the zoomable tree
    function zoom() {
        svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    }
    // define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents
    var zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3,1]).on("zoom", zoom);
    // define the baseSvg, attaching a class for styling and the zoomListener
    var baseSvg = d3.select("#tree-container").append("svg")
        .attr("width", viewerWidth)
        .attr("height", viewerHeight)
        .attr("class", "overlay")
        .call(zoomListener);

以下是我将默认缩放功能更改为平移的解决方案。我能找到各种各样的资源,包括一个关于stackoverflow的好帖子。

function panTo() {
    var current_translate = d3.transform(svgGroup.attr("transform")).translate;
    var dx = d3.event.wheelDeltaX + current_translate[0];
    var dy = d3.event.wheelDeltaY + current_translate[1];
    svgGroup.attr("transform", "translate(" + [dx,dy] + ")");
    d3.event.stopPropagation();
}
// Define the zoom function for the zoomable tree
function zoom() {
    svgGroup.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}

// define the zoomListener which calls the zoom function on the "zoom" event constrained within the scaleExtents
var zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3,1]).on("zoom", zoom);
// define the baseSvg, attaching a class for styling and the zoomListener
var baseSvg = d3.select("#tree-container").append("svg")
    .attr("width", viewerWidth)
    .attr("height", viewerHeight)
    .attr("class", "overlay")
    .call(zoomListener)
    .on("wheel.zoom",panTo) 
    .on("mousewheel.zoom", panTo)
    .on("DOMMouseScroll.zoom", panTo)