使用d3.js

时间:2017-05-30 15:15:24

标签: d3.js

我在D3.js中相当新。我想建立一个实时协作黑板。一个管理客户端在svg和其他客户端上绘制路径接收它们。我试图从客户端选择最后一个路径元素。我走了几个小时,找到了几个帖子How can I select :last-child in d3.js?,但无法使其发挥作用。当我问:

 console.log('svg ='+svg.selectAll("path")
已经绘制了两条路径

svg ={"_groups":[{"0":{},"1":{}}],"_parents":[{"__on":[{"type":"click","name":"","capture":false},{"type":"mousedown","name":"drag","capture":false},{"type":"touchstart","name":"drag","capture":false},{"type":"touchmove","name":"drag","capture":false},{"type":"touchend","name":"drag","capture":false},{"type":"touchcancel","name":"drag","capture":false}]}]}  

编辑:我的DOM结构

<svg id="myCanvas" width="960" height="500">
            <rect fill="#F2EDE4" width="100%" height="100%"></rect>
        <path fill="none" stroke="black" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" d="M223.64999389648438,304.25L223.98332722981772,304.5833333333333C224.31666056315103,304.9166666666667,224.98332722981772,305.5833333333333,226.31666056315103,306.75C227.64999389648438,307.9166666666667,229.64999389648438,309.5833333333333,231.14999389648438,310.4166666666667C232.64999389648438,311.25,233.64999389648438,311.25,234.98332722981772,310.4166666666667C236.31666056315103,309.5833333333333,237.98332722981772,307.9166666666667,238.81666056315103,307.0833333333333L239.64999389648438,306.25"></path><path></path></svg>

提前致谢

3 个答案:

答案 0 :(得分:2)

你尝试过这样的事吗?

const lastPath = d3.select('svg>path:last-child')

您应该能够在d3选择API中使用:last-child之类的字符串。

答案 1 :(得分:2)

彼得的answer 正在工作。

你得到一个{"_groups":[[{}]],"_parents":[{}]},就像你在your comment中所说的那样,因为这是 D3选择,而且这是预期的对象。

如果您想获取DOM元素,只需使用node()函数:

const lastPath = d3.select('svg>path:last-child').node();
//getting the DOM element -------------------------^

这是一个使用你的SVG的演示,它将记录那个空路径,这是最后一个(因为SO片段冻结 - 至少在我的机器中,使用Chrome - 当尝试记录D3选择时,here is a fiddle使用相同的代码):

&#13;
&#13;
const lastPath = d3.select('svg>path:last-child').node();
console.log(lastPath)
&#13;
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg id="myCanvas" width="960" height="500">
  <rect fill="#F2EDE4" width="100%" height="100%"></rect>
  <path fill="none" stroke="black" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" d="M223.64999389648438,304.25L223.98332722981772,304.5833333333333C224.31666056315103,304.9166666666667,224.98332722981772,305.5833333333333,226.31666056315103,306.75C227.64999389648438,307.9166666666667,229.64999389648438,309.5833333333333,231.14999389648438,310.4166666666667C232.64999389648438,311.25,233.64999389648438,311.25,234.98332722981772,310.4166666666667C236.31666056315103,309.5833333333333,237.98332722981772,307.9166666666667,238.81666056315103,307.0833333333333L239.64999389648438,306.25"></path>
  <path></path>
</svg>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这就是为我解决此问题的原因。根据{{​​3}}文档,这是您应该执行的操作:

var lastPath = d3.selectAll('svg>path').filter(':last-child');