d3.zoom不会缩放

时间:2018-02-27 13:31:37

标签: angular d3.js electron

我尝试使用放大D3实现树视图但没有成功。 它显示树,但缩放只是不起作用。由于某种原因,它不响应任何鼠标滚轮运动。没有编译错误。

 constructor(private element: ElementRef) {
    this.htmlElement = this.element.nativeElement;
    this.host = D3.select(this.element.nativeElement);
 }
  draw(issue) {
    if (!issue) {
      return;
    }
    var zoom = D3.zoom()
      .scaleExtent([1, 10])
      .on("zoom", this.zoomed);

    var nodes = D3.hierarchy(issue, function (d) {
      return d.children;
    });

    nodes = this.treemap(nodes);

    var svg = this.host.append('svg')
      .attr("width", this.width + this.margin.left + this.margin.right)
      .attr("height", this.height + this.margin.top + this.margin.bottom);
    var g = svg.append("g")
      .attr("transform",
        "translate(" + this.margin.left + "," + this.margin.top + ")")
        .call(zoom);
    this.container = svg;

    var link = g.selectAll(".link")
      .data(nodes.descendants().slice(1))
      .enter().append("path")
      .attr("class", "link")
      .attr("d", function (d) {
        return "M" + d.y + "," + d.x
          + "C" + (d.y + d.parent.y) / 2 + "," + d.x
          + " " + (d.y + d.parent.y) / 2 + "," + d.parent.x
          + " " + d.parent.y + "," + d.parent.x;
      });

    var node = g.selectAll(".node")
      .data(nodes.descendants())
      .enter().append("g")
      .attr("class", function (d) {
        return "node" +
          (d.children ? " node--internal" : " node--leaf");
      })
      .attr("transform", function (d) {
        return "translate(" + d.y + "," + d.x + ")";
      });

    node.append("circle")
      .attr("r", 10);

    node.append("text")
      .attr("dy", ".35em")
      .attr("x", function (d) { return d.children ? -13 : 13; })
      .style("text-anchor", function (d) {
        return d.children ? "end" : "start";
      })
      .text(function (d) { return d.data.name; });
  }

  zoomed() {
    this.container.attr("transform", "translate(" + this.host.event.translate + ")scale(" + this.host.event.scale + ")");
  }
}

我不确定问题是什么。任何帮助表示赞赏。 :)

1 个答案:

答案 0 :(得分:1)

zoomed()函数需要从d3获取事件,尝试

  • zoomed范围
  • 中声明draw
  • 将缩放事件附加到g而不是svg
  • 从d3

    获取event.transform
    zoomed() {
        g.attr("transform", d3.event.transform);
     }