D3.js调整大小并拖动

时间:2017-04-04 08:31:09

标签: javascript d3.js svg

我正在用D3画一棵树。当页面调整大小时,我想将树移动到特定位置(基本上在svg的左侧空间,以便树保持可见)。 我用这个代码

function resize() {
  svg
    .attr("width", getWidth())
    .attr("height", getHeight());
  svg.attr("transform", "translate(" + (window.innerWidth / 3) + "," + ((window.innerHeight / 3)) + ")" + " scale(1)");
  var zoom = d3.behavior.zoom();
  zoom.translate([window.innerWidth / 3, window.innerHeight / 3]);
}
d3.select(window).on('resize', resize);

这很好用,但是当我开始点击拖动图表时,它会作为起始拖动点移动到原始位置。 这是拖动功能:

function redraw() {
  if (!d3.event.sourceEvent) return;
    d3.event.sourceEvent.stopPropagation();
    svg.attr("transform",
      "translate(" + d3.event.translate + ")" +
      " scale(" + d3.event.scale + ")");
}

var svg = d3.select("#graph").append("svg")
        .attr("id", "graph")
        .attr("width", getWidth())
        .attr("height", getHeight())
        .call(zm = d3.behavior.zoom().on("zoom", redraw)).on("dblclick.zoom", null)
        .append("g")
        .attr("transform", "translate(" + initialWidth + "," + initialHeight + ")");

有关如何解决此问题的任何提示?

1 个答案:

答案 0 :(得分:1)

将缩放设为这样的全局变量:

var zoom = d3.behavior.zoom().on("zoom", redraw);

并在调整大小和缩放svg时使用它,如下所示。

更改1:

var svg = d3.select("#graph").append("svg")
        .attr("id", "graph")
        .attr("width", getWidth())
        .attr("height", getHeight())
        .call(zoom).on("dblclick.zoom", null)
        .append("g")
        .attr("transform", "translate(" + initialWidth + "," + initialHeight + ")")

更改2:

function resize() {
            svg
                .attr("width", getWidth())
                .attr("height", getHeight());
            svg.attr("transform", "translate(" + (window.innerWidth / 3) + "," + ((window.innerHeight / 3)) + ")" + " scale(1)");
            zoom.translate([window.innerWidth / 3, window.innerHeight / 3]);
        }