【问题标题】:What is causing this line to be repeatedly drawn in Angular/D3.js?是什么导致这条线在 Angular/D3.js 中重复绘制?
【发布时间】:2016-06-17 12:30:48
【问题描述】:

我正在使用这个很棒的教程来学习如何将 D3.js 库与 AngularJS 一起使用:http://briantford.com/blog/angular-d3。本教程按提供的方式工作(感谢 Brian!)

但我正在努力学习/理解这段代码,以便我可以破解它并绘制我想要的东西。我只是在包含var bars = layers.selectAll("g.bar") 的行之前添加了以下代码块:

    console.log('Setup');
    var grid = layers.selectAll("g.grid")
        .data(function(d) { return d; })
        .enter().append("g")
        .attr("class", "grid")
        .attr("transform", function(d) {
          console.log("1");
          return "translate(" + x(d) + ",0)";
        });

    console.log('About to draw a line');
    grid.append("line")          // attach a line
      .style("stroke", "green")  // colour the line
      .attr("x1", 100)     // x position of the first end of the line
      .attr("y1", 50)      // y position of the first end of the line
      .attr("x2", 300)     // x position of the second end of the line
      .attr("y2", 150);

我希望这会画出一条对角绿线。相反,它绘制了 700 多条对角绿线(见下面的截图)。为什么?我没有看到任何会导致这种情况的 forwhile 循环。那么为什么会这样呢?我在上面插入了 console.log 行。它打印了一次About to draw line。但它打印了1 702 次。为什么?这是plunker

【问题讨论】:

  • 在线181 你在网格上附加一条线,这是一个巨大的东西数组,因此它在每个网格元素上附加了线。你应该只在你想要的元素:)
  • 我不知道你想把它附加到哪里,但是如果你把它附加到 layers var 上,你会得到一行 plnkr.co/edit/IYRuHptmpf08GTa8t03s?p=preview

标签: javascript angularjs d3.js


【解决方案1】:

这一行:

grid.append("line")  

在网格中附加一条线,这意味着您正在使用网格中的相同数据。因为你的网格是这样的:

var grid = layers.selectAll("g.grid")
        .data(function(d) { return d; })

它使用来自层的相同数据:

var layers = vis.selectAll("g.layer")
            .data(data)

因此,此数据的长度为 18,但每个数据都有一个包含 39 个元素的数组,因此 18x39=702 即您拥有的行数。

基本上你想将该行附加到vis 而不是网格,否则你将使用相同的数据。

vis.append("line")          // attach a line
          .style("stroke", "green")  // colour the line
          .attr("x1", 100)     // x position of the first end of the line
          .attr("y1", 50)      // y position of the first end of the line
          .attr("x2", 300)     // x position of the second end of the line
          .attr("y2", 150);

更新的 Plnkr:https://plnkr.co/edit/MTQ9pNWL2784jPfRWH5F?p=preview

【讨论】:

  • 追问:在我画线的时候,怎么才能找到画布的宽高?
  • 画布是 svg 吗?
  • 给它一个id:svg.attr('id','svgContainer);然后通过 javascript 获取宽度: document.getElementById('svgContainer').width; ?这就是你想要的?
  • 嗯。不太对。我添加了属性,然后插入了这个:console.log('About to draw a line. SVG width = ', document.getElementById('svgContainer').width);。这产生了这个:drive.google.com/file/d/0B1UFylbhbG2eVHhHYlZkTFhRcVk/…
  • 我的错,我把 JQuery 和 JS 混淆了,而不是宽度,放 clientWidth 或 offsetWidth :) offsetWidth 包括边框宽度,clientWidth 没有。
猜你喜欢
  • 2013-08-18
  • 1970-01-01
  • 2020-01-22
  • 1970-01-01
  • 2019-11-01
  • 1970-01-01
  • 2011-08-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多